2012-01-30 47 views
9

我正在尋找下差異的解釋:的PowerShell 2.0命令行重定向

考慮下面的PowerShell腳本foo.ps1

write-host "normal" 
write-error "error" 
write-host "yay" 

運行它

C:\>powershell .\foo.ps1 > out.txt 2>&1

產品:

normal 
C:\foo.ps1 : error 
At line:1 char:10 
+ .\foo.ps1 <<<< 
    + CategoryInfo   : NotSpecified: (:) [Write-Error], WriteErrorException 
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,foo.ps1 

Write-Host : The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 co 
de or another FileStream. This may cause data loss. 
At C:\foo.ps1:3 char:11 
+ write-host <<<< "yay" 
    + CategoryInfo   : NotSpecified: (:) [Write-Host], IOException 
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.WriteHostCommand 

但隨着運行:

C:\>powershell .\foo.ps1 2>&1 > out.txt

主要生產(正確):

normal 
C:\foo.ps1 : error 
At line:1 char:10 
+ .\foo.ps1 <<<< 
    + CategoryInfo   : NotSpecified: (:) [Write-Error], WriteErrorException 
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,foo.ps1 

yay 

我幾乎解決了自己,以爲重定向的命令在Windows要緊,但是所有的TechNet usage page for command redirection中的示例顯示stderr重定向之前的文件重定向。

有人可以向我解釋這個嗎?

作爲參考,這是正在對服務器2003的x64 SP2做與:

C:\>powershell get-host 


Name    : ConsoleHost 
Version   : 2.0 
InstanceId  : 53c90e87-ded1-44f9-8e8d-6baaa1335420 
UI    : System.Management.Automation.Internal.Host.InternalHostUserInterface 
CurrentCulture : en-US 
CurrentUICulture : en-US 
PrivateData  : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy 
IsRunspacePushed : False 
Runspace   : System.Management.Automation.Runspaces.LocalRunspace 

,並使用寫輸出端產生相同的結果。

(這個問題是關係到我的解決this工作。)

+1

我不知道答案,但我確實知道Write-Host的處理方式與所有其他Write cmdlet不同。我現在避免像瘟疫一樣。用寫輸出來嘗試你的測試。 – EBGreen 2012-01-30 15:35:10

+0

感謝您的提示!不幸的是,發生了相同的結果。 – 2012-01-30 15:49:45

+1

寫輸出和寫主機有非常不同的用途。 Write-Host將信息(文本)寫入PowerShell主機。寫輸出將對象寫入PowerShell管道,然後可以通過接受管道輸入的命令截獲和處理該對象。如果不使用這樣的命令,則對象輸出也被呈現給主機。 – 2012-01-30 17:29:19

回答

1

這看起來像在PowerShell 2.0中的錯誤。我試圖用PowerShell 3.0預覽進行復制,現在按預期工作。

+0

你有一個...更快樂的答案? – 2012-01-30 19:49:55

+0

升級到CTP,將問題報告給Msft 2012-01-30 20:04:39