0

I just want to ask for some guidance/help as to why I am not getting any results when I query the variable for the array I used

Background on what I want to achieve is this. I am trying to gather details for a SSL Certificate that is about to expire. Before I display the total list. I want to first store it in an array and later on after the "IF" statement, that's the time I will display the complete list. My script is below. I am a newbie on scripting. I am not getting any errors but there is no result. Your advice will really be a big help

$DaysBeforeExpiry=90
$Rep = @()
$Expiry = Get-ChildItem -Path cert: -Recurse | Where-Object { $_.PSIsContainer }

ForEach-Object {
    $obj = New-Object PSObject
    $Daysleft = $Cert.NotAfter - (get-date)
    $obj | Add-Member -Membertype NoteProperty -Name "Path" $cert.PSParentPath
    $obj | Add-Member -Membertype NoteProperty -Name "Issuer" $cert.Issuer
    $obj | Add-Member -Membertype NoteProperty -Name "NotAfter" $cert.NotAfter
    $obj | Add-Member -Membertype NoteProperty -Name "DaysLeft" $DaysLeft
    foreach ($cert in $Expiry) {   
        if ($cert.notafter -le (get-date).Adddays($DaysBeforeExpiry) -and  $cert.notafter -gt (get-date)) {
            $Rep +=$obj   
        }
    }
}

$Rep
1
  • 3
    Foreach-Object is meant for pipeline input. Commented May 16, 2022 at 2:59

1 Answer 1

1

You should be able to narrow down your code using Where-Object to filter for those certs as they are passed down the pipeline:

$today = Get-Date
Get-ChildItem -Path "cert:" -Recurse | 
    Where-Object -FilterScript { (-not $_.PSIsContainer) -and $_.NotAfter -le $today.AddDays(90) -and $_.NotAfter -gt $today } | 
    Select-Object -Property "Issuer", "NotAfter", @{Name="Path";Expression={$_.PSParentPath}}, @{Name="DaysLeft";Expression={$_.NotAfter - $today}}

Used Select-Object and a calculated property rather than using a loop to create a pscustomobject with properties that are already there to select those properties.

As for what you tried, you would have to pipe to Foreach-Object and reference the current pipeline item using $_, or $PSItem which neither were specified to include the pipe (|) itself. Adding to fixed arrays (+=) can be computationally expensive when it comes to large lists so it's best to avoid it . Instead, take advantage of PowerShell's pipeline streaming and assign the output directly to a variable: $variable = foreach ($item in $list) { ... }.

Sign up to request clarification or add additional context in comments.

1 Comment

might want to include a check for -not $_.PSIsContainer to target only certificates

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.