Created
December 30, 2014 18:21
-
-
Save lazywinadmin/c1e7945b09a32fd7b147 to your computer and use it in GitHub Desktop.
Get Uptime of remote computers
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
# Jeff Hicks | |
# http://www.petri.com/creating-advance-functions-powershell.htm?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Petri+%28Petri+IT+Knowledgebase%29 | |
Function Get-MyUptime { | |
[cmdletbinding()] | |
Param( | |
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)] | |
[ValidateNotNullorEmpty()] | |
[Alias("cn","host")] | |
[string[]]$Computername = $env:Computername | |
) | |
Begin { | |
Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" | |
} #begin | |
Process { | |
Foreach ($computer in $computername) { | |
Write-Verbose "Getting uptime from $($computer.toupper())" | |
Try { | |
$Reboot = Get-CimInstance Win32_OperatingSystem -ComputerName $computer -ErrorAction Stop | Select-Object CSName,LastBootUpTime | |
} | |
Catch { | |
Write-Error $_ | |
} | |
if ($Reboot) { | |
Write-Verbose "Calculating timespan from $($reboot.LastBootUpTime)" | |
#create a timespan object and pipe to Select-Object | |
New-TimeSpan -Start $reboot.LastBootUpTime -End (Get-Date) | | |
Select-Object @{Name = "Computername"; Expression = {$Reboot.CSName}}, | |
@{Name = "LastRebootTime"; Expression = {$Reboot.LastBootUpTime}},Days,Hours,Minutes,Seconds | |
#reset variable so it doesn't accidentally get re-used, especially when using the ISE | |
Remove-Variable -Name Reboot | |
} | |
} #foreach | |
} #process | |
End { | |
Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" | |
} #end | |
} #end function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment