2011-11-03 85 views
1

我想弄清楚如何捕獲以下PowerShell代碼行的錯誤消息(例如,如果運行腳本的用戶沒有權限讀取文件):PowerShell:爲[IO.File]捕獲錯誤:: ReadAllText

[IO.File]::ReadAllText("C:\[test].txt") 

隨着Get-Content,我可以簡單地指定ErrorActionErrorVariable參數。上述代碼行似乎不是這種情況。

謝謝!

+0

注意使用PowerShell v3的+,您就能得到上述內容爲字符串:'獲取內容C:\ [測試] .TXT -Raw'。 v3中增加了參數'-Raw'。如果沒有這個'(Get-Content c:\ [test] .txt).GetType()。Name'將返回Object []'(將文件的所有行讀入數組),而不是單個'String'。 –

回答

1

使用try ... catch塊

try{ 

    [IO.File]::ReadAllText("C:\blah") 
} 
catch{ 
    #handle here. Catch specific exceptions as well. 
} 
+0

謝謝!我最終在catch塊中使用了'$ _。Exception.InnerException'。 – Nick