Networking/ServerTools.ps1

<#
    .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'
  }
}