Networking/ServerTools.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<#
    .NOTES
    ===========================================================================
     Created with: SAPIEN Technologies, Inc., PowerShell Studio 2019 v5.6.156
     Created on: 1/29/2019 12:46
     Created by: jisodl0
     Organization: J.B. Hunt
     Filename: ServerTools.ps1
    ===========================================================================
    .DESCRIPTION
        Contains functions used for managing/maintaining J.B. Hunt servers.
#>



<#
.SYNOPSIS
  Restart a service used by J.B. Hunt.

.DESCRIPTION
  Restarts the given service on the given computer so long as you have the
necessary permissions. This is done by retrieving the service from the given
computer name, stopping that service, then starting it back up. Each step
requires confirmation before continuing to the next to avoid any issues.

.PARAMETER ServiceName
  The name of the service to restart on the given server.

.PARAMETER ComputerName
  The name of the computer/server to restart the given service on.

.EXAMPLE
  PS C:\> Restart-JBService -ServiceName 'tomcat*' 'JVPWEB10101'

.EXAMPLE
  PS C:\> Restart-JBService tomcat* JVPWEB10101

.EXAMPLE
  PS C:\> Restart-JBService 'Razer Chroma*' 'JVPWEB10101'
#>

function Restart-JBService {
  [CmdletBinding(PositionalBinding = $true)]
  [Alias('rsjb')]
  param (
    [Parameter(Mandatory = $true,
               Position = 0,
               HelpMessage = 'Which service would you like to restart?')]
    [Alias('Service')]
    [System.String]
    $ServiceName,
    
    [Parameter(Mandatory = $true,
               Position = 1,
               HelpMessage = 'Which computer would you like to reset the service on?')]
    [Alias('Computer', 'ServerName', 'Server')]
    [System.String]
    $ComputerName
  )
  
  # Pull all services with the service name and on the given computer.
  $Service = Get-Service -Name $ServiceName -ComputerName $ComputerName
  
  # If more than one service was found, get the one the user wants to restart.
  if ($Service.Length -gt 1) {
    $Services = @()
    
    for ($x = 0; $x -lt $Service.Length; $x++) {
      [hashtable]$Data = @{
      }
      
      $Data.Add('Index', $x)
      $Data.Add('Status', $Service[$x].Status)
      $Data.Add('Name', $Service[$x].Name)
      
      $DataTable = New-Object -TypeName System.Management.Automation.PSObject -Property $Data
      $Services += $DataTable
    }
    
    # Write out the headers for the services.
    Write-Host "`nIndex Status Name"
    Write-Host '----- ----- ----'
    
    # Write the table of services to the console.
    $Services | ForEach-Object {
      Write-ServiceOut $_
    }
    
    # Get the index of the correct service to restart.
    $Index = Read-Host "`nWhich service would you like to restart? (0 - $x)"
    
    # Set the Service variable to the correct service.
    $Service = $Service[$Index]
  }
  
  # Write out the headers for the service.
  Write-Host "`nIndex Status Name"
  Write-Host '----- ----- ----'
  
  # Write the selected service to the console for verification.
  Write-ServiceOut $Service
  
  # Verify this is the correct service.
  $CorrectService = Read-Host -Prompt "`nIs this the correct service? (Y/N)"
  
  # Make sure the user response is lowercase.
  if ($CorrectService.Length -gt 0) {
    $CorrectService = $CorrectService.ToLower()
  }
  
  if ($CorrectService.StartsWith('y') -or ($CorrectService.Length -eq 0)) {
    # Stop the requested service.
    Stop-Service $Service
    
    # Verify the user wishes to continue with the "restart".
    $ContFlag = Read-Host -Prompt 'Continue with restart? (Y/N)'
    
    # Make sure the user response is lowercase.
    if ($ContFlag.Length -gt 0) {
      $ContFlag = $ContFlag.ToLower()
    }
    
    if ($ContFlag.StartsWith('y') -or ($ContFlag.Length -eq 0)) {
      Start-Service $Service
    }
  }
}

function Write-ServiceOut {
  param (
    [Parameter(Mandatory = $true,
               Position = 0)]
    $Service
  )
  
  # Write the index number to the console.
  Write-Host " $($Service.Index)" -ForegroundColor Yellow -NoNewline
  
  # Write the status to the console.
  if ($Service.Status -eq 'Running') {
    # If the service is running, output the text as green.
    Write-Host " $($Service.Status) " -ForegroundColor Green -NoNewline
  } elseif ($Service.Status -eq 'Stopped') {
    # If the service is stopped, output the text as red.
    Write-Host " $($Service.Status) " -ForegroundColor Red -NoNewline
  }
  
  Write-Host $Service.Name
}

<#
.SYNOPSIS
  Clears the logs on a given server that are older than 14 days or whatever is
provided.

.DESCRIPTION
  Clears any log files found on the server that are older than 14 days and
  removes them. This is usually done when a server is reporting a lack of free
  disk space.

.PARAMETER ComputerName
  The name of the server to clear logs from.

.PARAMETER FileAge
  How many days old a file must be to be deleted.

.EXAMPLE
  PS C:\> Clear-Logs -ComputerName 'JVPWEB11001'
This example clears the logs older than 14 days on the JVPWEB11001 server.

.EXAMPLE
  PS C:\> Clear-Logs 'JVPWEB11001' 21
This example clears the logs older than 21 days on he JVPWEB11001 server.
#>

function Clear-Logs {
  [CmdletBinding(ConfirmImpact = 'High')]
  param (
    [Parameter(Mandatory = $true,
               Position = 0,
               HelpMessage = 'Which server would you like to clear old logs on?')]
    [Alias('Name')]
    [System.String]
    $ComputerName,
    
    [Parameter(Mandatory = $false,
               Position = 1,
               HelpMessage = 'How many days old must a log file be?')]
    [ValidateRange(7, 999)]
    [Alias('Age')]
    [int]
    $FileAge = 15
  )
  
  BEGIN {
    $Path = "\\${ComputerName}\C$\APPL\logs\"
    $TotalBytes = 0
    $FileCount = 0
    $SizeGB = @{
      Name       = 'SizeGB';
      Expression = { $_.Size / 1GB -as [int] };
    }
    $FreeGB = @{
      Name       = 'FreeGB';
      Expression = { [Math]::Round($_.Freespace / 1GB, 2) }
    }
  }
  
  PROCESS {
    Write-Verbose "Getting files to be deleted..."
    
    # Get all log files at the provided path.
    $AllLogFiles = Get-ChildItem -Path $Path -Recurse -Include '*.log' -File
    
    # Get all files old enough to be cleared.
    $OldLogFiles = $AllLogFiles | Where-Object CreationTime -lt (Get-Date).AddDays($FileAge * -1)
    
    # See if any files old enough have been found.
    if ($OldLogFiles.Length -eq 0) {
      Write-Host 'There were no files found that were old enough to delete.'
    } else {
      # Count the files and get the total size to be cleared.
      foreach ($LogFile in $OldLogFiles) {
        $TotalBytes += $LogFile.Length
        $FileCount++
        
        Write-Verbose "$($LogFile.Name) marked for deletion..."
      }
      
      # Output key info to user.
      $TotalGB = $TotalBytes/1GB
      $RoundedSize = ([math]::Round($TotalGB, 2))
      
      Write-Host "Amount of space being cleared: ${RoundedSize}GB"
      Write-Host "Number of files being deleted: $FileCount"
      
      # Get the continue state from the user.
      Resolve-ContinueState -LogFiles $OldLogFiles
      
      # Display the drive stats.
      $WmiRes = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'" -ComputerName $ComputerName
      $WmiRes | Select-Object PSComputerName, DeviceID, $SizeGB, $FreeGB
    }
  }
}

<#
.SYNOPSIS
  Evaluates the continue state and acts accordingly.

.DESCRIPTION
  Evaluates the provided ContinueState parameter to determine what the user
wants to do about clearing the logs and then does it.

.PARAMETER LogFiles
  An array/collection of files to be handled.

.NOTES
  A "private" function in that it isn't ever exported and is only used by the
Clear-Logs cmdlet.
#>

function Resolve-ContinueState {
  [CmdletBinding()]
  [OutputType([System.String])]
  param (
    [Parameter(Mandatory = $true,
               Position = 0)]
    [Alias('Files')]
    [System.Array]
    $LogFiles
  )
  
  if ($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
    $ContinueState = Read-Host "$([Environment]::NewLine)How would you like to proceed?$([Environment]::NewLine)[C]ontinue/[Q]uit"
  } else {
    $ContinueState = Read-Host "$([Environment]::NewLine)How would you like to proceed?$([Environment]::NewLine)[L]ist Files/[C]ontinue/[Q]uit"
  }
  
  if ($ContinueState.ToLower() -eq 'l') {
    $LogFiles | ForEach-Object { Write-Host $_.FullName }
    Resolve-ContinueState -LogFiles $LogFiles
  } elseif (($ContinueState.ToLower() -eq 'c') -or ($ContinueState.Length -eq 0)) {
    $LogFiles | ForEach-Object {
      Write-Verbose "Removing $($_.Name)..."
      Remove-Item $_ -Force
    }
    return 'c'
  }
}