0

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

3

1 Answer 1

2

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:

  • I'm using calculated properties in the Select-Object line to get the properties you need
  • By surrounding $Rep in the last line with @(), you are forcing the variable to be an array, so you can use its .Count property safely
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.