如何在PowerShell中测试无效路径?

时间:2013-04-09 11:01:34

标签: powershell path

我有一个脚本试图使用相对路径运行一些可执行文件 所以我使用test-path来验证可执行文件是否应该在哪里。 如果没有,我会尝试其他地点。

if(test-path "$current../../../myexe.exe"){
   # found it!
}

但在这种情况下,如果$ current为C:/folder/,那么test-path "C:/folder/../../../myexe.exe"将失败

  

路径......指的是基础'C:'

之外的项目

是否有一种干净且可靠的方法来测试路径,以便它返回true或false,并且不会给我一些意外错误?

4 个答案:

答案 0 :(得分:2)

Test-Path ([io.path]::Combine($current,(Resolve-Path ../../../myexe.exe)))

有关详细信息,请参阅this thread

答案 1 :(得分:2)

我使用.NET File.Exists让它工作,但如果你想要正确地解析相对路径,你必须先设置Environment.CurrentDirectory

编辑:在Shay Levy指出它对其他后台进程可能会有危险之后,不会更改CurrentDirectory(请参阅http://www.leeholmes.com/blog/2006/06/26/current-working-directory-with-powershell-and-net-calls/

[环境] :: CurrentDirectory = $ pwd

[System.IO.File].Exists("$pwd\$invalidRelativePath")
False

答案 2 :(得分:2)

测试路径从根本上被打破。

即使 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"
}

答案 3 :(得分:0)

您应该使用Resolve-Path或Join-Path