powershell 2.0 command line redirection

跟風遠走 提交于 2019-12-21 04:24:09

问题


I'm looking for an explanation of the following discrepancy:

Given the following powershell script foo.ps1:

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

Running it with

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

Produces:

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

But running with:

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

Produces (correctly):

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

I almost resolved myself into thinking that the order of the redirection mattered in Windows, however all of the examples in the TechNet usage page for command redirection show the file redirection preceding the stderr redirection.

Can someone please explain this to me?

For reference, this is being done on Server 2003 x64 SP2 with:

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

and using write-output produces the same result.

(This question is related to my work in solving this.)


回答1:


That looks like a bug in PowerShell 2.0. I tried reproducing with the PowerShell 3.0 preview and it now works as expected.



来源:https://stackoverflow.com/questions/9065296/powershell-2-0-command-line-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!