Reputation: 33
I would like to ask for some help regarding an incrementing value applied in the script below For each certificate it found, a counter increments by 1, I tried usig $i=0; $i++ but I'm not getting anywhere.
$Expiry = Get-ChildItem -Path cert: -Recurse
$Rep= @()
Foreach ($cert in $Expiry)
{
if ($cert.notafter -le (get-date).Adddays(120) -AND $cert.notafter -gt (get-date))
{
$obj = New-Object PSObject
$Daysleft = $Cert.NotAfter - (get-date)
$obj | Add-Member -type NoteProperty -Name "Path" $cert.PSParentPath
$obj | Add-Member -type NoteProperty -Name "Issuer" $cert.Issuer
$obj | Add-Member -type NoteProperty -Name "NotAfter" $cert.NotAfter
$obj | Add-Member -type NoteProperty -Name "DaysLeft" $Daysleft.Days
$Rep +=$obj
}
}
My goal here is if it satisfies the condition, it will display the certificate and a counter will be plus 1. until it completes the loop then it displays the total certificates found
Hoping for your help
Thank you
Upvotes: 0
Views: 500
Reputation: 61013
You don't need a loop counter for this, or even a loop if you use Select-Object
to return objects with the chosen properties like this:
# It's up to you, but personally I would use $today = (Get-Date).Date to set this reference date to midnight
$today = Get-Date
$Expiry = Get-ChildItem -Path cert: -Recurse
$Rep = $Expiry | Where-Object { $_.NotAfter -le $today.AddDays(120) -and $_.NotAfter -gt $today |
Select-Object @{Name = 'Path'; Expression = {$_.PSParentPath}},
Issuer, NotAfter,
@{Name = 'DaysLeft'; Expression = {($_.NotAfter - $today).Days}}
}
# to know howmany items you now have, use
@($Rep).Count
Note:
Select-Object
line to get the properties you need$Rep
in the last line with @()
, you are forcing the variable to be an array, so you can use its .Count
property safelyUpvotes: 2