What I am doing here is generating XML output that PRTG can parse when it runs the script. The script is intended to determine when the last windows update install happened. It works fine for all remote servers, but when it runs on the local machine, it's not getting the correct $value. It ends up being null, rather than an integer. I assume I'm missing something here as to how Invoke-Command works on a local server vs a remote server. Would anyone mind showing me where I made a mistake?
$ErrorActionPreference = "Stop"
#Get a list of servers
$servers = Get-ADComputer -SearchBase 'DC=<removed>,DC=int' -Filter {OperatingSystem -NotLike "Windows Server 2003*"} | Sort Name | Select -ExpandProperty Name
$value = ""
#This is the start of the XML output that PRTG will be parsing when the code runs
Write-Host "<prtg>"
#Loop through all servers and attempt to get a value for last windows update install.
foreach($server in $servers) {
Write-Host "`t<result>`n`t<channel> $server </channel>"
try {
Invoke-Command -ComputerName $server -ScriptBlock {
$props = @{
LastDetect = Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Detect’ -Name LastSuccessTime | select -ExpandProperty LastSuccessTime
LastInstall = Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Install’ -Name LastSuccessTime | select -ExpandProperty LastSuccessTime
}
$stringdato = $props.LastInstall;
$DATO = ([datetime]::ParseExact($stringdato, "yyyy-MM-dd HH:mm:ss", $null))
$today = (Get-Date)
$timeout = ($today - $DATO)
$value = $timeout.Days
}
} catch {
# set value to 999 if there is a problem, for PRTG's error threshold.
$value = 999
}
Write-Host "`t<value>$value</value>"
Write-Host "`t<CustomUnit>days</CustomUnit>`n`t<LimitMaxError>90</LimitMaxError>`n`t<LimitMaxWarning>60</LimitMaxWarning>`n`t<LimitMode>1</LimitMode>`n`t</result>`n"
}
Write-Host "</prtg>"