Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Retrieve Last bootup information
- .DESCRIPTION
- This function will connect to remote computers to retrieve their last boot timestamp.
- .PARAMETER ComputerName
- Name of computer system to query
- .PARAMETER Credential
- Credential object to use when connecting to remote computers
- .EXAMPLE
- PS C:\> Get-PCUptime -ComputerName 'server1','server2'
- This example will connect to the two computers listed and retrieve their last boot time
- information using the security context of the user running the script
- .EXAMPLE
- PS C:\> $cred = Get-Credential
- Get-PCUptime -ComputerName 'server1','server2' -Credential $cred
- This example will connect to the two computers listed and retrieve their last boot time
- information using the security context of the credential created when calling Get-Credential
- .NOTES
- Additional information about the function.
- #>
- function Get-PCUptime
- {
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory = $true)]
- [ValidateNotNullOrEmpty()]
- [string[]]$ComputerName,
- [ValidateNotNullOrEmpty()]
- [pscredential]$Credential
- )
- begin
- {
- #no prep work needed for this function
- }
- process
- {
- foreach ($name in $ComputerName)
- {
- # use splatting to add credential parameter if present when called
- $obj = New-Object psobject -Property @{
- ComputerName = $name;
- LastBootUpTime = $null;
- Uptime = $null
- }
- try
- {
- #any exception in this block causes script to fall back to DCOM for connection to remote server
- $arguments = @{
- ComputerName = $name;
- ErrorAction = 'Stop'
- }
- if ($Credential)
- {
- $arguments.Add('Credential', $Credential)
- }
- $session = New-CimSession @arguments
- $OS = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem -ErrorAction Stop
- }
- catch
- {
- try
- {
- $SessionOption = New-CimSessionOption -Protocol DCOM
- $arguments = @{
- ComputerName = $name;
- ErrorAction = 'Stop';
- SessionOption = $SessionOption
- }
- if ($Credential) { $arguments.Add('Credential', $Credential) }
- $session = New-CimSession @arguments
- $OS = Get-CimInstance -CimSession $session -ClassName Win32_OperatingSystem -ErrorAction Stop
- }
- catch
- {
- 'Connection to server {0} failed' -f $name | Write-Error
- }
- }
- try
- {
- $LastBootTime = $OS | Select-Object -ExpandProperty LastBootUpTime
- $obj.LastBootUpTime = $LastBootTime
- $obj.Uptime = New-TimeSpan -Start $LastBootTime -End (get-date)
- $obj
- }
- catch
- {
- 'Unable to retrieve last boot time on server {0}' -f $name | Write-Error
- $obj
- }
- }
- }
- end
- {
- # no cleanup code needed in this function
- }
- }
- if (!$cred) { $cred = Get-Credential}
- Get-PCUptime -ComputerName 'miw059wt-cmtest','miw070wt-cmtest' -Credential $cred
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement