2013-04-09 31 views
0

我有一个脚本,试图使用相对路径运行一些可执行文件。
因此,我使用test-path来验证可执行文件应该在哪里。 如果不是,我尝试另一个位置。如何测试PowerShell中的无效路径?

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

但在这种情况下,如果$电流C:/folder/然后test-path "C:/folder/../../../myexe.exe"失败

的路径...提到,这是基地外的项目 'C:'

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

回答

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

更多信息,请参见this thread

+0

我刚得到它的工作,我用[IO.File] ::是否存在(),我认为,解决路径将引发同一类型的异常 – 2013-04-09 11:27:23

+0

的我不会改变进程的工作目录,HTTP ://www.leeholmes.com/blog/2006/06/26/current-working-directory-with-powershell-and-net-calls/ – 2013-04-09 11:55:20

+0

有趣的话,我应该使用[IO.Path] :: GetFullPath( “$ pwd \ .. \ .. \ myexe.exe”),以避免解决路径异常,然后File.Exists以避免测试路径的异常 – 2013-04-09 12:17:52

0

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

2

测试路径是fu根本打破。

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

解决之道在于迫使它在测试的路径要炸毁返回$假。

if ($(Try { Test-Path $MyPath.trim() } Catch { $false })) { #Returns $false if $null, "" or " " 
    write-host "path is GOOD" 
} Else { 
    write-host "path is BAD" 
}