我正在寻找以下差异的解释:
给出以下 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 使用页面 http://technet.microsoft.com/en-us/library/bb490982.aspx显示 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 https://stackoverflow.com/questions/8978052/powershell-2-0-redirection-file-handle-exception.)