Property bag error

I was writing a PowerShell script to alert on soon-to-expire certificates from the local computer store but kept getting this error:

A terminating error occurred. Error output: (Value does not fall within the expected range.).

Here's the abbreviated code, solution noted in red:

$MomApi=New-Object -comObject MOM.ScriptAPI # MOMScriptAPI object.
$date=(get-date)
$Certificates=Get-ChildItem -Path Cert:\LocalMachine\Root\ | Sort-Object -Unique
foreach ($Certificate in $Certificates) {
[DateTime]$NotAfter=$Certificate.NotAfter
if ($NotAfter -gt $date) {
[int]$CountCerts=$CountCerts + 1
$Thumbprint=$Certificate.Thumbprint
[DateTime]$NotBefore=$Certificate.NotBefore
$IssuedTo=$Certificate.GetNameInfo([System.Security.Cryptography.X509Certificates.X509NameType]::SimpleName, $false) # $True maps to IssuedBy column, $False maps to IssuedTo column in the Certificates mmc console.
$StringNotBefore=$NotBefore.ToString("yyyy/MM/dd HH:mm:ss")
$StringNotAfter=$NotAfter.ToString("yyyy/MM/dd HH:mm:ss")
$Bag = $MomApi.CreatePropertyBag() # Add this line in the loop, not outside.
$Bag.AddValue('IssuedTo', $IssuedTo)
$Bag.AddValue('Thumbprint', $Thumbprint)
$Bag.AddValue('NotAfter', $ThumNotAfterbprint)
$MomApi.Return($Bag)
}
#$Bag
}

Comments