QuickBlog – PowerShell function to get system last bootup time.

Here’s a simple function that will get your system last bootup time.  Also, notice that I’m using the ‘-ErrorVariable ‘ parameter wth a given variable name ‘MyError‘ to trap any error messages during the execution of the ‘Get-WMIobject’ command.  That the same time I’m including the ‘-ErrorAction SilentlyContinue‘ so my function won’t abort while executing.

For the only argument needed in this function, I’m validating that the passing argument is not null (or empty).  Then, to build my result I’m using the scriptblocks to customized the results to be displayed on screen.

At the end, I’m collecting all thre information into the ‘$SvrRebooted‘ variable so it can be diaplayed when done.

[sourcecode language=”powershell”]
function Get-SystemLastBootUpTime{
[Parameter(Mandatory=$True, Position=0)][ValidateScript({$_ -ne $null})] [Array] $ComputerName
[Array] $SvrRebooted = $null;

$SvrRebooted = foreach($name in $ComputerName)
$x = get-wmiObject -Class Win32_OperatingSystem -Computername $name `
-ErrorAction ‘SilentlyContinue’ -ErrorVariable MyError;

if($($MyError | Select exception) -eq $Null)
$x | Select-Object `
@{Label = ‘ComputerName’; Expression = {$_.csname}}, `
@{Label = ‘Operating System’; Expression = {[string] (($_.Name).Split(‘|’)[0]);}}, `
@{Label = ‘MyLastBootUpTime’; Expression = {$_.ConvertToDateTime($_.LastBootUpTime)};}, `
@{Label = ‘Status’; Expression = {"Success"}};
$name | Select-Object `
@{Label = ‘ComputerName’; Expression = {$name}}, `
@{Label = ‘Operating System’; Expression = {$null}}, `
@{Label = ‘MyLastBootUpTime’; Expression = {$null}}, `
@{Label = ‘Status’; Expression = {‘Failed – ‘ `
+([string]([string] $MyError[0]).split("`n")).split("(E")[0];}};


This function builds an array object.  Then you can use the ‘Format-Table‘ or the ‘Format-List‘ at your discretion. To execute the ‘Get-SystemLastBootUpTime’ function look at the following one-liners:

[sourcecode language=”powershell”]
## – Running the function:
[array] $svrList = @("Server1","Desktop2");
Get-SystemLastBootUpTime -ComputerName $svrList | Format-Table -AutoSize;
## – or
Get-SystemLastBootUpTime -ComputerName $svrList | Format-List;