Home > Software design >  Convert Foreach-Object to classic foreach
Convert Foreach-Object to classic foreach

Time:10-11

I'm trying to create a script who retrieve certificate installed on IIS server. And then send the time remaining (in days) before expiration.

I found this script

$CertAll=Get-ChildItem -Path Cert:\LocalMachine\My
$CertInUse=Get-Childitem -Path IIS:\SslBindings
$CertSame=Compare-Object -ReferenceObject $CertAll -DifferenceObject $CertInUse -Property ThumbPrint -IncludeEqual -ExcludeDifferent
$CertSame | foreach{Get-Childitem –path Cert:\LocalMachine\My\$($_.thumbprint)} | Select-Object @{n=’ExpireInDays’;e={($_.notafter – (Get-Date)).Days}}

I want to change it with a 'classic' foreach. So, I tried this:

$CertAll=Get-ChildItem -Path Cert:\LocalMachine\My
$CertInUse=Get-Childitem -Path IIS:\SslBindings
$CertSame=Compare-Object -ReferenceObject $CertAll -DifferenceObject $CertInUse -Property ThumbPrint -IncludeEqual -ExcludeDifferent

Foreach ($element in (Get-Childitem –path Cert:\LocalMachine\My\$($CertSame.thumbprint))) {

    Select-Object @{n=’ExpireInDays’;e={($CertSame.notafter – (Get-Date)).Days}}
    #command to send value

}

But it's not working...

Thanks in advance

CodePudding user response:

The ForEach-Object (alias foreach) in the original code actually loops over $CertSame, so you have to replicate that using the foreach() statement as well:

foreach( $Cert in $CertSame ) {
    foreach( $ChildCert in Get-Childitem –path Cert:\LocalMachine\My\$($Cert.thumbprint) ) {
        $ChildCert | Select-Object @{n=’ExpireInDays’;e={($_.notafter – (Get-Date)).Days}}
    }   
}

CodePudding user response:

Thanks a lot, but I don't receive the right value. Here is what i got with the original script :

ExpireInDays
------------
         311
          74

What I got with the new script :

Thumbprint                                Subject                                                                                                                                             
----------                                -------                                                                                                                                             
91365BBBE0104494AA9C1C7413595B8B7395F05A  CN=*.zetes.be                                                                                                                                       
98F20A03831CAE8895E8F39E369A07CAAC161C88  CN=*.zetes.com   
  • Related