This repository has been archived by the owner on Jul 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathGet-LastBootTime.ps1
99 lines (83 loc) · 3.15 KB
/
Get-LastBootTime.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
###############################################################################################################
# Language : PowerShell 4.0
# Filename : Get-LastBootTime.ps1
# Autor : BornToBeRoot (https://github.com/BornToBeRoot)
# Description : Get the time when a computer is booted
# Repository : https://github.com/BornToBeRoot/PowerShell
###############################################################################################################
<#
.SYNOPSIS
Get the time when a computer is booted
.DESCRIPTION
Get the time when a computer is booted.
.EXAMPLE
Get-LastBootTime -ComputerName Windows7x64
ComputerName LastBootTime
------------ ------------
Windows7x64 8/21/2016 3:25:29 PM
.LINK
https://github.com/BornToBeRoot/PowerShell/blob/master/Documentation/Function/Get-LastBootTime.README.md
#>
function Get-LastBootTime
{
[CmdletBinding()]
param(
[Parameter(
Position=0,
HelpMessage='ComputerName or IPv4-Address of the remote computer')]
[String[]]$ComputerName=$env:COMPUTERNAME,
[Parameter(
Position=1,
HelpMessage='Credentials to authenticate agains a remote computer')]
[System.Management.Automation.PSCredential]
[System.Management.Automation.CredentialAttribute()]
$Credential
)
Begin{
$LocalAddress = @("127.0.0.1","localhost",".","$($env:COMPUTERNAME)")
[System.Management.Automation.ScriptBlock]$ScriptBlock = {
$LastBootTime = (Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property LastBootUpTime).LastBootUpTime
return [DateTime]$LastBootTime
}
}
Process{
foreach($ComputerName2 in $ComputerName)
{
if($LocalAddress -contains $ComputerName2)
{
$LastBootTime = Invoke-Command -ScriptBlock $ScriptBlock
}
else
{
if(Test-Connection -ComputerName $ComputerName2 -Count 2 -Quiet)
{
try {
if($PSBoundParameters.ContainsKey('Credential'))
{
$LastBootTime = Invoke-Command -ScriptBlock $ScriptBlock -ComputerName $ComputerName2 -Credential $Credential -ErrorAction Stop
}
else
{
$LastBootTime = Invoke-Command -ScriptBlock $ScriptBlock -ComputerName $ComputerName2 -ErrorAction Stop
}
}
catch {
Write-Error -Message "$($_.Exception.Message)" -Category InvalidData
continue
}
}
else
{
Write-Error -Message """$ComputerName2"" is not reachable via ICMP!" -Category ConnectionError
continue
}
}
[pscustomobject] @{
ComputerName = $ComputerName2
LastBootTime = $LastBootTime
}
}
}
End{
}
}