Last active
September 12, 2016 10:26
-
-
Save markwragg/e873167fccd09656bf36d848f7995bd0 to your computer and use it in GitHub Desktop.
Powershell script for getting the uptime of multiple Windows servers using WMI : http://wragg.io/get-uptime-from-multiple-servers/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -version 2.0 | |
[CmdletBinding()] | |
param ( | |
[ValidateSet("London","Berlin","Tokyo","")][string]$location | |
) | |
Write-Host ("`n" * 5) | |
Import-Module ActiveDirectory -Cmdlet get-adcomputer | |
$Servers = get-adcomputer -filter {Enabled -eq $true -and OperatingSystem -Like "Windows*"} -property Enabled,OperatingSystem | ?{$_.DistinguishedName.contains($location)} | |
$Errs = @() | |
$Count = 0 | |
$Servers | ForEach-Object{ | |
$computer = $_ | |
$ErrMsg = $null | |
Write-Progress -Activity "Attempting to get uptime value for $($computer.name)" -Status "$Count of $($Servers.Count) completed" -PercentComplete ($Count/$Servers.Count*100) | |
If(Test-Connection $computer.name -TimeToLive 5 -Quiet -Count 1 -ErrorAction SilentlyContinue){ | |
If($os = Get-WmiObject -ComputerName $computer.name win32_operatingsystem -ErrorAction SilentlyContinue){ | |
$Uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime)) | |
$Display = "Up " + $Uptime.Days + " days, " + $Uptime.Hours + " hours, " + $Uptime.Minutes + " minutes" | |
Write-Verbose "$($computer.name) : $($computer.operatingsystem) : $Display" | |
New-Object -TypeName PSObject -Property @{Name=$computer.name;OS=$computer.operatingsystem;Uptime=$Display;Days=$Uptime.Days;Hours=$Uptime.Hours;Minutes=$Uptime.Minutes;} | |
}Else{$ErrMsg = "Failed to get uptime"} | |
}Else{$ErrMsg = "Failed to ping"} | |
#Trap Error | |
If ($ErrMsg -ne $null){ | |
$Err = New-Object System.Object | |
$Err | Add-Member -type NoteProperty -name Name -value $computer.name | |
$Err | Add-Member -type NoteProperty -name Error -value $ErrMsg | |
Write-Warning "$($Err.Name) : $($Err.Error)" | |
$Errs += $Err | |
} | |
$Count++ | |
} | Select Name,OS,Uptime,Days,Hours,Minutes | Sort Days,Hours,Minutes -Descending | Export-Csv "Uptime-$location-$(get-date -format yyyy-MM-dd).csv" -NoTypeInformation | |
#Write Errors to file | |
If ($Errs -ne $null){$Errs | Select Name,Error | Export-Csv "Uptime-$location-$(get-date -format yyyy-MM-dd)-Errors.csv" -NoTypeInformation} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment