New to powershell and my foreach keeps failing. Trying to iterate over a list of cert files but it fails. Probably simple

0

Problem:

When I import a cert individually, outside of a foreach, it prints the thumbprint as needed; however, I need to iterate through a list of .cer files on a fileshare so that I can run them against a local machine's currently installed certs. The moment I try to run the list of certs through my foreach, it fails.

Working code (individually)

<# Notice the explicite .cer file #>
$certGet = Get-ChildItem -Path \\fileserver\...\Certs\cert.cer

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certGet)
$cert.Thumbprint

I am trying to scale this working code out into a foreach to iterate over a list or .cer files. Below is my attempt thus far.

Failing code:

$certGetList = Get-ChildItem -Path \\fileserver\...\Certs

$certGetList | ForEach-Object {
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cert.Import($_)
    $cert.Thumbprint
}

Error message

ERROR: Exception calling "Import" with "1" argument(s): "The system cannot find the file specified.
ERROR: "
list_thumbprints_test.ps1 (18, 2): ERROR: At Line: 18 char: 2
ERROR: +     $cert.Import($_)
ERROR: +     ~~~~~~~~~~~~~~~~
ERROR:     + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
ERROR:     + FullyQualifiedErrorId : CryptographicException
ERROR:

Tucker

Posted 2018-04-03T19:50:08.747

Reputation: 51

do you see anything if you simply put Write-Host $_ at the beginning of your foreach? – EBGreen – 2018-04-03T19:54:23.970

Yes, it prints the file within the current iteration just before printing the error message. Example: "cert1.cer" + error message and then "cert2.cer" + error message. The error message shown above actually comes up for each iteration that fails. – Tucker – 2018-04-03T20:03:07.957

I also attempted to import $_ as a string via .import("$_"), but resulted in the same error. I am totally stumped at this point. – Tucker – 2018-04-03T20:14:15.690

Answers

1

Of course... so simple.

Answer:

$cert.Import($certGetList + "\" + $_)

Somehow, it loses the origin of the object and tries to find the relative file locally, instead of on the network share. I needed to explicitly direct it to the network share for each iteration.

Tucker

Posted 2018-04-03T19:50:08.747

Reputation: 51