Windows PowerShell获取文件系统证书过期日期失败及证书对比问题
问题分析与解决方法
不需要将证书导入证书存储就能获取其过期日期,你的问题出在脚本读取文件系统CRT证书的语法错误,导致无法正确解析证书对象。
原脚本的错误点
读取文件系统证书的代码$desCertFile = Get-ChildItem Cert:\>C: -Path $filePathCRT完全错误:
Cert:\是PowerShell专门用于访问证书存储的虚拟驱动器,不能用来读取本地文件系统的CRT文件- 语法中的
>是多余的错误字符,路径写法不符合PowerShell规范
正确读取文件系统CRT证书的方法
对于本地文件系统中的CRT证书,只需将其解析为X509Certificate2对象即可获取所有证书属性(包括过期日期NotAfter),有两种常用方式:
方式1:使用New-Object构造证书对象
$desCertFile = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($filePathCRT)
方式2:使用Get-PfxCertificate命令
该命令不仅支持PFX格式证书,也兼容CRT格式的公钥证书:
$desCertFile = Get-PfxCertificate -FilePath $filePathCRT
修正后的完整脚本
$certName = "websitename.com" $exportPath = "C:\" # 用Join-Path拼接路径,避免手动拼接导致的格式错误 $filePathCRT = Join-Path -Path $exportPath -ChildPath "$certName.crt" $certSource = "CN=$certName" # 获取证书存储中的目标证书 $srcCertFile = Get-ChildItem Cert:\LocalMachine\WebHosting | Where-Object { $_.Subject -eq $certSource } if (-not $srcCertFile) { Exit } # 读取并解析文件系统中的CRT证书 try { $desCertFile = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($filePathCRT) } catch { Write-Output "读取CRT文件失败:$_" Exit } if (-not $desCertFile) { Write-Output "cannot get cert file" } # 对比两个证书的过期日期 if ($srcCertFile.NotAfter -ne $desCertFile.NotAfter) { Write-Output "certs not the same" Write-Output "存储中证书过期日期:$($srcCertFile.NotAfter)" Write-Output "文件中证书过期日期:$($desCertFile.NotAfter)" } else { Write-Output "两个证书过期日期一致" }
特殊情况处理:PEM格式CRT文件
如果你的CRT文件是PEM格式(带有-----BEGIN CERTIFICATE-----和-----END CERTIFICATE-----头部),直接使用上述方法可能无法解析,需要先去除头部并转换为字节数组:
# 读取PEM格式证书并转换 $certContent = Get-Content $filePathCRT -Raw -Encoding Ascii # 去除头部、尾部和换行符 $cleanedContent = $certContent -replace "-----BEGIN CERTIFICATE-----", "" -replace "-----END CERTIFICATE-----", "" -replace "\r\n", "" # 转换为字节数组 $certBytes = [System.Convert]::FromBase64String($cleanedContent) # 创建证书对象 $desCertFile = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certBytes)
内容的提问来源于stack exchange,提问作者b.sullender
相关产品推荐
相关产品推荐

