powershell - 如果特定证书文件 .crt 或 .cer 等已安装并处于事件状态

标签 powershell

如果已安装来自驱动器上特定路径的特定证书(例如“c:\path\MyCert.crt”)并且它是否处于事件状态,我在尝试获取时遇到困难。

我有以下内容:

$crt = New-Object System.Security.Cryptography.X509Certificates.X509Certificate;
$crt.Import("c:\path\MyCert.crt");
write-host "MyCert.crt expires after: " $crt.GetExpirationDateString();
$crt.GetName();

显示:

MyCert.crt 过期时间:11/12/2021 2:12:31 AM C=..., O="...", OU=..., OU="...", CN=...

尝试过:

[bool](dir cert:\LocalMachine\ | ? { $_.subject -like "cn=MyCert" })

但不确定这是否告诉我它是否已安装并处于事件状态?

有人可以帮忙吗

最佳答案

就像@TessellatingHeckler 建议的那样,您应该比较指纹,因为这会告诉您是否安装了特定 证书。否则,即使证书已续订​​或发生其他事情更改了证书,您最终也只能得到一个真实值。

您会遇到的另一个问题是,默认情况下,Get-ChildItem(别名 DIR)不会递归地向下搜索路径,因此您只会看到通过运行示例中的内容,证书可以存在于内部:

[1] PS C:\> dir cert:\LocalMachine\


Name : TrustedPublisher

Name : ClientAuthIssuer

Name : Remote Desktop

Name : Root

Name : TrustedDevices

Name : CA

...

您还会注意到,将 crt 文件导入为“X509Certificate”对象不会显示指纹。你在这里有两个选择,使用 Get-PfxCertificate 查看文件(我不确定这是什么时候引入的,所以我不确定你是否可以使用它),或者你可以将 crt 文件作为“X509Certificate2”对象导入。

请原谅我在您的代码段中扩展了别名,但以下内容可以解决问题:

$crt = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$crt.Import('c:\certs\CertFile.crt');

[bool](Get-ChildItem cert:\LocalMachine\ -Recurse | Where { $_.Thumbprint -eq $crt.Thumbprint })

关于powershell - 如果特定证书文件 .crt 或 .cer 等已安装并处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41471200/

相关文章:

C# 到 Powershell

powershell - Powershell查找注册表项并将其删除

powershell - 用于获取虚拟机端口的Azure powershell命令

powershell - PowerCLI - 通过 VM IP 查找虚拟机

arrays - 作为System.Object []发送的PowerShell V5 Invoke-RestMethod数组

Powershell : Update properties file with key = value

powershell - 使用 powershell 脚本添加自定义 header

windows - Powershell 中的 FindWindow 给我 0(在 w11 22h2 FR 上): unattended character in the title of a cmd elevated console?

powershell - 通过 PowerShell 在 IIS 中设置应用程序设置

excel - 使用 PowerShell 从 Excel 文件中读取注释