Powershell 5 說“No way Jose”,不能用 null 或空字串連接路徑。我說為什么不呢?有沒有辦法在不添加更多 if-else 塊的情況下讓 join-path 更加“靈活”?
$its_in_the_path = $true
#$its_in_the_path = $false
if ($its_in_the_path) {
$mydir = ""
}
else {
$mydir "C:\tool\path
}
$tool = join-path $mydir "runit.exe"
Cannot bind argument to parameter 'Path' because it is an empty string.
daskljdhgfaklsuhfalhfluwherfluqwhrluq2345214723452345h2kjrwefqy345
At ~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidData: (:) [frunsim], ParameterBindingValidationException
FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,frunsim
uj5u.com熱心網友回復:
Join-Path將不允許$null值或[string]::Empty. 你可以使用Path.Combine Method:
PS \> [System.IO.Path]::Combine($null, "runit.exe")
runit.exe
PS \> [System.IO.Path]::Combine('C:\', 'Documents', "runit.exe")
C:\Documents\runit.exe
uj5u.com熱心網友回復:
圣地亞哥Squarzon的有用的答案你如何解決節目無法通過$null或''以Join-Path通過直接使用.NET API的。
另一種方法是Join-Path完全繞過:
$tool = $mydir ('', '\')[[bool] $mydir] "runit.exe"
以上依賴于這樣一個事實,即$null和''(空字串),當強制為布林值 ( [bool]) 時,回傳$false,而任何非空字串都回傳$true。反過來,當用作陣列索引( [...]) 時,$false映射到 index0和- 請參閱此答案的底部$true以1了解PowerShell 到布爾轉換規則的摘要。
在PowerShell中(核心)7 可以更清晰地表達這個意圖,使用 ?:的三元條件運算子,依靠事實上,這兩個$null和''也含蓄地轉換為$false在布爾環境:
$tool = $mydir ($mydir ? '\' : '') "runit.exe"
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/346006.html
標籤:电源外壳
下一篇:為什么點源運算子將字串轉換為命令
