locked
How to skip a server check in foreach command in powershell RRS feed

  • General discussion


  • I have a powershell script to check server health for a list of servers. However, the script waits for output for a server (have some reachability issues) and doesnt move to next and keeps on waiting. How to make the script to skip a server if it takes long time.

    Here is the script:


    $DirectoryToSaveTo = "D:\Wintel\Script\"
    $date=Get-Date -format "d-MM-yyyy"
    $Filename="CTX servers healthcheck-$($date)"

    $Computers = Get-Content "D:\Wintel\Script\servers.txt"
     
    $a = New-Object -comobject Excel.Application
    $a.visible = $True
    $a = $a.Workbooks.Add()
    $c = $a.Worksheets.Item(1)

    $intRow = $row
    $xlOpenXMLWorkbook=[int]51

     
    $c.Cells.Item(1,1) = "Machine Name"
    $c.cells.item(1,2) = "Server Status"
    $c.cells.item(1,3) = "Processor Utilization %"
    $c.cells.item(1,4) = "Memory Utilization %"


    $intRow = 2

     
    $colComputers = get-content "D:\Wintel\Script\Servers.txt"
    foreach ($strComputer in $colComputers)
    {


    $TotalRAM = (get-WMIObject win32_operatingsystem -computername $strComputer | Measure-Object TotalVisibleMemorySize -sum).sum / 1024
    $FreeRAM = ((get-WMIObject -computername $strComputer -class win32_operatingsystem).freephysicalmemory) / 1024
    $UsedRAM = (($TotalRAM) - ($FreeRAM))
    $RAMPercentUsed = ([math]::truncate(($UsedRAM) / ($TotalRAM) * 100))

    $c.cells.item($introw, 4) = "$RAMPercentUsed %"

     

     

    $c.cells.item($introw, 2) = if ( Test-Connection -ComputerName $strComputer -Count 1 -ErrorAction SilentlyContinue )
        {
                $wmi = gwmi Win32_OperatingSystem -computer $strComputer
          $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
          [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
          Write-output "Server is Pinging & Uptime is $($uptime.days) Days $($uptime.hours) Hours $($uptime.minutes) Minutes"
        }
                 else {
                    Write-output "Server is not pinging"
    }

    $CPU = (Get-WmiObject win32_processor -ComputerName $strComputer | Measure-Object -property LoadPercentage -Average).Average
    $c.cells.item($introw, 3) = "$CPU %"

    }
     
     
    $filename = "$DirectoryToSaveTo$filename.xlsx"
    if (test-path $filename ) { rm $filename }
    $c.UsedRange.EntireColumn.AutoFit()
    $a.SaveAs($filename, $xlOpenXMLWorkbook)
    $a.Saved = $True
    $a.Close()
    $a.DisplayAlerts = $False
    $erroractionpreference = “SilentlyContinue”

    Wednesday, January 20, 2016 2:15 PM

All replies