测试路径从根本上被破坏了。
甚至SilentlyContinue也坏了:
Test-Path $MyPath -ErrorAction SilentlyContinue
如果 $MyPath 为 $null、空或不作为变量存在,这仍然会爆炸。
如果 $MyPath 只是一个空格,它甚至会返回 $true。那个“”文件夹到底在哪里!
以下是适用于以下情况的解决方法:
$MyPath = "C:\windows" #Test-Path return $True as it should
$MyPath = " " #Test-Path returns $true, Should return $False
$MyPath = "" #Test-Path Blows up, Should return $False
$MyPath = $null #Test-Path Blows up, Should return $False
Remove-Variable -Name MyPath -ErrorAction SilentlyContinue #Test-Path Blows up, Should return $False
解决方案在于在 Test-Path 想要炸毁时强制它返回 $False。
if ( $(Try { Test-Path $MyPath.trim() } Catch { $false }) ) { #Returns $false if $null, "" or " "
write-host "path is GOOD"
} Else {
write-host "path is BAD"
}