使用 powershell 调用本机命令行应用程序并捕获 STDERR

使用 powershell 调用本机命令行应用程序并捕获 STDERR

我在 Windows 上使用 cygwin 工具的移植,该工具将正常状态消息写入 STRERR。从 PowerShell 运行时,这会产生丑陋的输出:

PS> dos2unix.exe -n StartApp.sh StartApp_fixed.sh
dos2unix.exe : dos2unix: converting file StartApp.sh to file StartApp_fixed.sh in UNIX format ...
At line:1 char:13
+ dos2unix.exe <<<<  -n StartApp.sh StartApp_fixed.sh
    + CategoryInfo          : NotSpecified: (dos2unix: conve...UNIX format ...:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

有没有更好的办法?

PS 我打算发布我找到的一个解决方案并将其与其他人的答案进行比较。

答案1

唉。这种丑陋是 Powershell 的一个设计缺陷 :( 如果应用程序打印到标准错误(并且其他任何东西都在监听),则 Powershell 会将每一行包装在一个模糊的“NativeCommandError”对象中。参见https://stackoverflow.com/questions/1394084/ignoring-an-errorlevel-0-in-windows-powershell更多详细信息

你可以让丑陋的对象保持沉默,但你也会失去有用的内容。

答案2

我相信我刚刚偶然发现了一个比@yzorg 的解决方案更简洁的解决方案。将 stderr 重定向到 stdout 是不够的,因为此时它仍然是一个 ErrorRecord 对象,而不是字符串。相反,它需要是进程,而下面的代码似乎可以用最少的努力提取所需的内容:

PS> dos2unix.exe -n StartApp.sh StartApp_fixed.sh 2>&1 | %{"$_"}
dos2unix: converting file StartApp.sh to file StartApp_fixed.sh in Unix format...

答案3

这是我找到的一个解决方案。如果您有更好的答案,请发布您的答案(这仅适用于将状态消息发送到 STDERR 而不是正常输出流的命令行实用程序):

PS> $output = dos2unix.exe -n StartApp.sh StartApp_fixed.sh 2>&1
$output.CategoryInfo.TargetName | Out-Default
dos2unix: converting file StartApp.sh to file StartApp_fixed.sh in UNIX format ...

相关内容