我正在創建一個函式,我想驗證傳遞給我的函式的字串是否是格式正確的路徑。Test-Path 確定路徑是否存在,這是我不想要的。是否有可以執行此操作的 RegEx 運算式?還是其他一些本機 Cmdlet?
謝謝。
uj5u.com熱心網友回復:
您可以使用Test-Path -IsValid來檢查有效但不存在的路徑:
Test-Path -LiteralPath 'C:\Whatever' -IsValid
不過,問題在于“有效”似乎與“格式正確”的意思不同。
例如,如果我使用D:\Whatever它在我的機器上也有效,而E:\Whatever不是;因為沒有這樣的 PSDrive(但是C并且D存在)。
同樣奇怪的WSman:\whatever是Falsewhile HKCU:\whateveris True。
它似乎認為 UNC 路徑是有效的。
如果您打算嘗試以另一種方式驗證路徑,您可以從一組無效字符開始,您可以使用[System.IO.Path]::InvalidPathChars.
但這里的東西太奇怪,這些字符中的一個§,然而C:\§whatever回報True從Test-Path -IsValid。
我在這里提出的問題可能多于答案。
來自評論:
我希望使用驅動器號和可能的目錄驗證完全限定的路徑。"C:\SomeDirectory\ 或 D:\blah\blah"
我認為這里要做的最直接的事情可能是首先檢查路徑是否“扎根”,然后將其轉換為[DirectoryInfo]物件:
if ([System.IO.Path]::IsPathRooted($path)) {
# this will throw an exception if the path can't be used
# for example Z:\whatever is accepted, ZZ:\whatever is not
$validatedPath = ([System.IO.DirectoryInfo]$path).FullName
}
else {
throw [System.ArgumentException]"Only fully-qualified paths are accepted."
}
您還可以選擇保留[DirectoryInfo]物件而不是使用 將其“轉換”回字串.FullName,因為該物件具有許多有用的屬性和方法,即使目錄不存在也是如此。
$path = 'Z:\whatever' -as [System.IO.DirectoryInfo]
$path | Format-List *
$path | Get-Member
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326785.html
上一篇:替換字符向量中的"
下一篇:無法在C中設定空字串的第二個元素
