2017-07-13 36 views
2

如何重定向PowerShell的重定向標準錯誤和stdout到兩個不同的地方

  • 標準錯誤記錄到logfile
  • 標準輸出爲對象

事情我已經看了看:

>>2>>只重定向到文件。
-RedirectStandardOutput-RedirectStandardError只能重新定向到文件。
| Out-File無法重定向stderr。
| Tee-Object同樣的問題。

+3

'。 {$ object = command} 2>&1 | Out-File logfile' – PetSerAl

+0

@PetSerAl - 你能解釋一下嗎? '2> 1'會將輸出stdout和stderr重定向到日誌文件不是嗎? –

+1

是的。但賦值操作('$ object =')已經捕獲了常規輸出,所以它已經從輸出流中移除了。 –

回答

6

加入stdoutstderr輸出流的工作方式與PetSerAl評論類似,但語法並不是最直觀的。

2>&1的奇怪語法意味着stderr(流2)將被添加到stdout(流1)中。因爲這實際上不是你是什麼之後,嘗試從MS頁面適應其他例子PowerShell的:

或者,您可以將輸出重定向到一個地方,錯誤到另一個。

DIR file.xxx> output.msg 2> output.err

因此,

$ret = myCommand 2> errors.log 

應在$ret可變日誌文件和非錯誤發送錯誤。

+0

謝謝vonPryz。我用PowerShell找到的一個大問題是沒有找到關於該做什麼的文檔,而是「爲什麼」和「如何」工作。知道2>&1將stderr饋入stdout是關鍵。 –

2

關於about_Redirection MSDN文章的全面說明。

A Minimal, Complete, and Verifiable examplestdout到管):

PS D:\PShell> -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Output 
-15 
3 
7.5 

PS D:\PShell> Get-Content "$env:temp\err.txt" 
Attempted to divide by zero. 
At line:1 char:28 
+ -1,5,0,2| ForEach-Object { 15/$_ } 2>"$env:temp\err.txt" | Write-Outpu ... 
+       ~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [], RuntimeException 
    + FullyQualifiedErrorId : RuntimeException 


PS D:\PShell> 

又如(stdout反對):

PS D:\PShell> $x = -1,5,0,2| ForEach-Object { 15/$_} 2>"$env:temp\err.txt" 

PS D:\PShell> $x 
-15 
3 
7.5 
相關問題