Monthly Archive


Scripting Game puzzle – – January 2016

Here’s how I’d solve the puzzle

function get-starttime {
        [Alias('CN', 'Computer')]
        [string[]]$computername = $env:COMPUTERNAME
        foreach ($computer in $computername){
            $props = [ordered]@{
                ComputerName = $computer
                StartTime = ''
                'UpTime (Days)' = 0.0
                Status = 'OFFLINE'
            if (Test-WSMan -ComputerName $computer -ErrorAction SilentlyContinue) {
                $lbt = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer -ErrorAction SilentlyContinue
                if ($lbt) {
                    $props['StartTime'] = $lbt.LastBootUpTime
                    $upt = [math]::round(((Get-Date) - $lbt.LastBootUpTime).TotalDays, 1)
                    $props['UpTime (Days)'] = $upt
                    $props['Status'] = 'OK'
                else {
                    $props['Status'] = 'ERROR'
            } ## endif
            New-Object -TypeName PSObject -Property $props
        } ## end foreach
    } ## end PROCESS

Create an advanced function. Yes I know I’ve used lower case for the function name. I always do to visually separate my code from cmdlets and other functions.


Use the [parameter] decorator to enable pipeline input. Only a single parameter so don’t need to bother woth positional parameters. Function is supposed to default to local machien so can’t make parameter mandatory.


Requirement to process multiple computers at once presumably means the computername parameter has to take an array – sumultaneous processing implies a work flow which negates the initial requirement to create a function


Use the PROCESS block to run a foreach loop that iterates over the collection of computernames.


Create a hash table for the results – I’ve used an ordered hash table to preserve the property order. Set the values to a failed connection.


use Test-Wsman to see if can reach the computer. If can’t the output object is created. If you can reach the machine then run Get-CimInstance - preferred over Get-WmiObject because it returns the date ready formatted


Assuming that works set the start time and status properties. Calculate the uptime in days. I’d prefer to see  just an integer here – tenths of days doesn’t mean anything to most people


If the call to Get-CimInstance  fails then set the status to ERROR

Output the object.


The requirement to add a proeprty for patching is not clear but I’m assuming it means if the machine has been up for more than 30 days with the 1/10 month as a typo

if you want to add that then


Add a property

MightNeedPatching = $false

to the hash table when you create it


and add this line

if ($upt -ge 30){$props['MightNeedPatching'] = $true}


$upt = [math]::round(((Get-Date) - $lbt.LastBootUpTime).TotalDays, 1)
$props['UpTime (Days)'] = $upt

Comments are closed.