【问题标题】:powershell 2.0 command line redirectionpowershell 2.0 命令行重定向
【发布时间】:2012-02-22 07:56:57
【问题描述】:

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

给定以下 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:\&gt;powershell .\foo.ps1 2&gt;&amp;1 &gt; 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 重定向之前的文件重定向。

谁能给我解释一下?

作为参考,这是在 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的工作有关。)

【问题讨论】:

  • 我不知道答案,但我知道 Write-Host 的处理方式与所有其他 Write cmdlet 不同。我现在像避免瘟疫一样避免它。尝试使用 Write-Output 进行测试。
  • 感谢您的提示!不幸的是,同样的结果发生了。
  • Write-Output 和 Write-Host 有非常不同的用途。 Write-Host 将信息(文本)写入 PowerShell 主机。 Write-Output 将一个对象写入 PowerShell 管道,然后可以由接受管道输入的命令拦截和处理该对象。如果没有使用这样的命令,那么对象输出也会被渲染到主机。
  • 显然 cmd.exe 在两种不同的情况下表现不同。但是,由于没有记录该行为,因此将其作为问题的解决方案可能不是一个好主意。

标签: windows powershell command-line file-io powershell-2.0


【解决方案1】:

这看起来像是 PowerShell 2.0 中的一个错误。我尝试使用 PowerShell 3.0 预览进行复制,现在它可以按预期工作了。

【讨论】:

  • 你有...更满意的答案吗?
  • 升级到CTP,将问题报告给Msft
猜你喜欢
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 2014-01-05
  • 2014-07-21
  • 1970-01-01
相关资源
最近更新 更多