2012-04-13 37 views
8

我試圖驗證文件的存在,但問題在於文件名中的名稱中有括號,例如c:\ test [R] 10005404,Failed與評論,[S] SiteName.txt。

我嘗試使用字符串.replace方法沒有成功。

$a = c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt 
$Result = (Test-Path $a) 
# Returns $False even though the file exists. 

試過
$a = $a.Replace("[", "`[") 
$a = $a.Replace("]", "`]") 

$Result = (Test-Path $a) 
# Also returns $False even though the file exists. 

思想將不勝感激。 謝謝,聖油

+0

應該在路徑名稱周圍引用:'$ a ='c:\ test \ [R] 10005404,失敗並返回評論,[S] SiteName.txt''。這只是一個錯字,還是在你的代碼? – Rynant 2012-04-13 18:03:59

+0

舊的Windows [PowerShell本週提示](http://technet.microsoft.com/en-us/library/ff730956.aspx)解釋了原因和解決方法。這是一種重複的問題[powershell get-childitem無法處理文件名以[字符即使使用轉義字符]開頭(http://stackoverflow.com/a/9508802/608772) – JPBlanc 2012-04-14 04:45:40

回答

21

嘗試使用-LiteralPath參數:

Test-Path -LiteralPath 'C:\[My Folder]' 

方括號具有特殊的意義。

它實際上是一個POSIX功能,使你可以這樣做:

dir [a-f]* 

這將使你在當前目錄中以字母A開始通過F. Bash有相同功能的所有的事情。

5

至少有三種方法可以使其工作。

使用類似於您的方法的方法,使用雙引號時需要添加2個反引號,因爲在發送到Replace方法之前,單個反引號將評估爲轉義字符。

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt" 
$a = $a.Replace("[", "``[") 
$a = $a.Replace("]", "``]") 
$Result = Test-Path $a 

Replace方法中使用單引號還可以防止反引號被刪除。

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt" 
$a = $a.Replace('[', '`[') 
$a = $a.Replace(']', '`]') 
$Result = Test-Path $a 

最後,你可以使用LiteralPath參數,它不使用通配符(方括號通過PowerShell的是用來匹配定義的字符集可以匹配)。

$a = "c:\test\[R] 10005404, Failed with Comments, [S] SiteName.txt" 
$Result = Test-Path -LiteralPath $a 
+0

+1當需要時,前兩種是理想的解決方案在名稱中使用'* .txt'等通配符與文件或文件夾一起使用'['或']' – user66001 2018-03-07 07:06:07

相關問題