2013-04-09 51 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" 
}