繁体   English   中英

检查字符串是否为X509Store路径或PFX文件

[英]Check if string is X509Store path or PFX file

我需要检查字符串是证书存储区(例如"Cert:\\CurrentUser\\My" )还是pfx文件路径(例如"D:\\\\PFXfiles\\self-signed.pfx"

哪种方法更好,为什么? 每个优点/缺点是什么? 有没有更好的方法? 方法1:

if ($certLocation.ToUpper().Contains(".PFX"))
{
    #it's a .pfx file
}
else
{
    #it's a cert store
}

方法2:

if ((Resolve-Path -LiteralPath $certLocation).Provider.Name -eq "FileSystem")
{
    #it's a .pfx file
}
elseif ((Resolve-Path -LiteralPath $certLocation).Provider.Name -eq "Certificate"
{
    #it's a cert store
}

我会使用Split-Path

switch ((Split-Path $certLocation -Qualifier)) {
  'cert:' { 'cert store' }
  'c:'    { 'file path' }
  default { Write-Error "invalid provider: $_" }
}

如果需要,请检查“文件路径”脚本块中的扩展名。


您应该看到神奇的文件数量 ,我建议您使用Linux中存在的file命令,并且程序员为Windows提供该链接
看我的例子

C:\Program Files (x86)\GnuWin32\bin>file.exe c:\Users\soheil\Desktop\1.pfx
c:\Users\soheil\Desktop\1.pfx; data

C:\Program Files (x86)\GnuWin32\bin>file.exe c:\Users\soheil\Desktop\2.pfx
c:\Users\soheil\Desktop\2.pfx; empty

或像这样

C:\Program Files (x86)\GnuWin32\bin>file.exe c:\a.txt
c:\a.txt; UTF-8 Unicode (with BOM) English text, with very long lines, with CRLF
 line terminators

第一个1.pfx我使用IIS创建自签名
第二个2.pfx我将txt文件重命名为2.pfx
如果您想完全了解什么文件,则应使用file命令查看幻数

对我而言,测试字符串会更好,因为仅操作字符串而不是解析路径,创建另一个对象然后读取该对象的属性会更有效,但实际上,它不会更改任何内容。 我会做一些不同的事情。

if ($certLocation.Split(":")[0] -like "cert") { 
    #it's a cert store
}
else {
    #it's a pfx
}

我会鸣叫...如果您要测试字符串以查看路径在哪里,请使用Resolve-Path cmdlet,然后选择Provider属性。

$StringPath = "Cert:\CurrentUser\my","C:\Temp\fakecert.pfx"

Switch($StringPath){
    {(Resolve-Path $_|Select -Expand Provider).tostring() -eq "Microsoft.PowerShell.Security\Certificate"} {"$_ is in the Certificate Store";continue}
    {(Resolve-Path $_|Select -Expand Provider).tostring() -eq "Microsoft.PowerShell.Core\FileSystem"} {"$_ is in the File System"}
}

Cert:\CurrentUser\my is in the Certificate Store
C:\Temp\fakecert.pfx is in the File System

这样,PowerShell会告诉您它用来解析该路径的人。 如果您提供无效的路径,这将引发错误,但应为您提供有关项目存储位置的准确信息。 可以添加错误捕获来捕获无效路径,但这取决于您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM