2014-10-22 103 views
0

我有一個腳本被調用某種方式,我無法更改它。 我想將整個腳本的錯誤消息重定向到一個文件。這個怎麼用?將錯誤輸出重定向到腳本內的文件

我這樣做,它的工作原理,但誤差是完全消失了:

$ErrorActionPreference="SilentlyContinue" 
Start-Transcript -path C:\output.txt -append 

write-host "test" 

some nonsence that creates as error 

Stop-Transcript 

感謝

+0

您是否必須使用'Start-Transcript'?你的腳本被調用的方式是什麼?它是從命令行調用的'ps1'嗎? – arco444 2014-10-22 10:14:42

+0

腳本是否調用本機命令?即使它們顯示在命令行窗口中,Start-Transcript也不會實際記錄由本機命令生成的錯誤。您可以通過將呼叫轉接到外部主機來解決此問題。有關錯誤參考請參閱此處:https://connect.microsoft.com/PowerShell/feedback/details/315875/unable-to-capture-all-session-output-into-a-transcript – Paul 2014-10-22 10:27:43

+0

你好。我不知道你的意思是由本地命令。腳本從bat文件啓動,但同時啓動到多臺機器。這不會導致一個日誌文件與所有的機器登錄嗎? – user3019059 2014-10-22 11:06:24

回答

0

我需要這樣的事情之前,但我可以改變文件是如何被稱爲等

如果從所提到的命令行啓動,由arco444,您可以使用下面的管道一切一個文件:

PowerShell.exe -Command "& {c:\myscript.ps1}" > c:\myscript.log 
2

這會爲你工作嗎?

try{ 
    # your code goes here 
} 
catch{ 
    $exception = $_.Exception.Message 
    Out-File -FilePath 'c:\myscript.log' -Append -InputObject $exception 
} 
+0

你好。這似乎工作,但它是否正確腳本結束,如果一個錯誤消息被捕獲?它應該繼續。是否有可能也記錄所有命令tids這個文件?像成績單一樣嗎? – user3019059 2014-10-22 11:02:57

+0

是的。那是對的。發生異常的那一刻腳本將跳到catch。但是你可以將所有命令封裝在單獨的try-catch對中。它不會捕獲像轉錄本那樣的所有命令。也許你需要把兩者結合起來。 – ojk 2014-10-22 11:05:56

0

小心使用開始 - 抄本。您可能會收到以下錯誤:

Start-Transcript : This host does not support transcription. 
At D:\Apps\TranscriptTest\TranscriptTest.ps1:3 char:1 
+ Start-Transcript -Path Log.txt -Append 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotImplemented: (:) [Start-Transcript], PSNotSupportedException 
    + FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.StartTranscriptCommand