I came across the following bizarre behavior and I was hoping someone could point me to some documentation that can explain why this behavior happens or what is causing it.
I have tried looking at the documentation for New-SelfSignedCertificate
to see if there was a remark explaining this or a parameter that "forced" it to complete but didn't find anything useful. https://learn.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps
I also tried searching google for OutVariable vs assignment but didn't find anything helpful either.
Consider the following functions:
function Why-DoesThisFail {
$cert = New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
-CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
-KeyExportPolicy NonExportable;
# Note that this outputs fine.
Write-Host $cert.Thumbprint;
# Prints nothing
Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}
function Why-DoesThisPass {
New-SelfSignedCertificate -Type Custom -Subject "CN=test" -KeyAlgorithm "RSA" -KeyLength 2048 `
-CertStoreLocation "Cert:\CurrentUser\My" -NotAfter (Get-Date).AddDays(1) -KeySpec Signature `
-KeyExportPolicy NonExportable -OutVariable cert;
# Note that this outputs fine.
Write-Host $cert.Thumbprint;
# Prints Cert as expected
Get-ChildItem -Path "Cert:\CurrentUser\My\$cert.Thumbprint";
}
Notice that the only difference between the 2 functions is one is using variable assignment and one is using the OutVariable
. Is this a behavior of Powershell itself in how it is handling OutVariable vs assignment; or is this because of something that New-SelfSignedCertificate
is doing behind the covers? It feels almost as if the Certificate isn't being registered on the machine until after the New-SelfSignedCertificate
completes and it doesn't complete for some reason when variable assignment is used. Note that after the function completes and control is returned to Powershell, you can successfully run the last line (replacing the thumbprint with the one written from Write-Host) and retrieve the certificate from the machine.
I'm puzzled.
Thanks for any help!