Ritche Falle
Ritche Falle

Reputation: 33

Getting No Results When Using Array

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

Upvotes: 0

Views: 51

Answers (1)

Abraham Zinala
Abraham Zinala

Reputation: 4694

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) { ... }.

Upvotes: 1

Related Questions