[英]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.