使用powershell获取证书信息

使用powershell获取证书信息,powershell,ssl,powershell-core,Powershell,Ssl,Powershell Core,我的想法是让powershell代码既适用于windows,也适用于ubuntu,只需稍作更改(如get childitem中的路径),因此我在ubuntu上尝试了以下脚本,但在windows上无法运行,它显示了以下错误 openssl.exe:无法打开[主题] 第5行字符:10 $var=(&C:\OpenSSL-Win64\bin\OpenSSL.exe x509-in$File-dates-no 以下是我编写的代码: $files = get-childitem Cert:\Local

我的想法是让powershell代码既适用于windows,也适用于ubuntu,只需稍作更改(如get childitem中的路径),因此我在ubuntu上尝试了以下脚本,但在windows上无法运行,它显示了以下错误

openssl.exe:无法打开[主题]

第5行字符:10

  • $var=(&C:\OpenSSL-Win64\bin\OpenSSL.exe x509-in$File-dates-no
以下是我编写的代码:

$files = get-childitem Cert:\LocalMachine\My    
foreach ($File in $files) 
{ 
$var = ((& C:\OpenSSL-Win64\bin\openssl.exe x509 -in $File -dates -noout) - 
match 'notAfter')
Write-Host $var
}

另一句话:openssl使用什么语法来获取证书名

openssl x509-in
需要一个文件路径作为参数,而不是
[X509Certificate]
对象的自定义格式输出

您可以改为使用(base64)并将其传输到
openssl

if($IsWindows){
    foreach($cert in Get-ChildItem cert:\LocalMachine\My\) {
       # Write BEGIN line
       $certStrings  = @('-----BEGIN CERTIFICATE-----')

       # Export cert data
       $certData     = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)

       # Convert to Base64 + append
       $certStrings += [Convert]::ToBase64String($certData, [System.Base64FormattingOptions]::InsertLineBreaks)

       # Write END line
       $certStrings += '-----END CERTIFICATE-----'

       # Pass off to openssl.exe
       $NotAfter = @(($certStrings -join [System.Environment]::NewLine) | .\path\to\openssl.exe x509 -text -noout -dates) -match 'notAfter'

       Write-Host $NotAfter
    }
}
else {
    foreach($cert in Get-ChildItem cert:\LocalMachine\My\) {
        $notAfter = @(& path\to\openssl.exe x509 -in $cert -dates -noout) -match 'notAfter'
Write-Host $notAfter
    }
}

使用相同的代码,但使用自动变量来区分平台,
$IsWindows
$IsLinux
$IsMacOs
。即,
if($IsLinux){“Do Liux stuff”}elseif($IsMacOs){“Do OS X stuff”}else{“Do Windws stuff”}
Nice one。编码到base 64的转换是难以置信的。我在ubuntu上试过,但没有成功,它告诉我“方法调用失败,因为它不包含methode导出”,正如@LotPings指出的,你可以尝试用
$is*
自动变量检测平台,更新答案