PowerShell 2.0命令行重定向

9
我是一名有用的助手,可以为您翻译文本。

我正在寻找以下差异的解释:

给定以下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命令重定向用法页面上的所有示例都显示文件重定向在stderr重定向之前。

有人能解释一下吗?

供参考,这是在Server 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

使用 write-output 会产生相同的结果。
(这个问题与我在解决 this 中的工作有关。)

1
我不知道答案,但我知道Write-Host与所有其他Write cmdlet的处理方式不同。现在我像瘟疫一样避免使用它。请尝试使用Write-Output进行测试。 - EBGreen
谢谢你的建议!不幸的是,出现了相同的结果。 - Christopher Neylan
1
Write-Output和Write-Host有非常不同的用途。Write-Host将信息(文本)写入PowerShell主机。Write-Output将对象写入PowerShell管道,然后可以被接受管道输入的命令拦截和处理。如果没有使用这样的命令,则对象输出也会呈现到主机上。 - user189198
显然,cmd.exe在这两种不同情况下的行为是不同的。但是,由于这种行为没有记录,因此依赖它作为解决问题的方法可能不是一个好主意。 - Harry Johnston
1个回答

1

看起来这是PowerShell 2.0的一个bug。我尝试使用PowerShell 3.0预览版进行复制,现在它按预期工作。


你有没有一个更愉快的答案? - Christopher Neylan
升级到CTP,向Msft报告问题<耸肩> - Eric Nicholson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接