将npm / js文件的控制台输出转发到Powershell控制台

时间:2019-05-24 09:56:15

标签: powershell

在我的Powershell脚本中,我执行以下操作:

Write-Host (npm run onesky_script -- "param1" "param2" "param3") -Separator `n
// OR following
npm run onesky_script -- "param1" "param2" "param3" | Write-Host

在两种情况下,我在Powershell控制台中都得到以下输出:

> onesky@1.0.0 onesky_script C:\some\path
> node onesky.js "param1" "param2" "param3"

Some console output created by my js script via console.log

我想要的是以下输出(仅js脚本输出,而不是脚本调用):

Some console output created by my js script via console.log

我可以使用某些调用语法更改或替代语法来实现我想要实现的目标吗?

1 个答案:

答案 0 :(得分:0)

不要使用Write-Host,因为您要使用要发送到另一个项目的数据。如果您在PowerShellv5x以下,则Write-Host会清空缓冲区并且不支持管道。在v5中,它现在写入信息流。微软已经记录了一段时间。

  

http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful

     

...截至2016年5月,Jeffrey Snover改变了立场。

     

使用PowerShell v5 Write-Host不再“杀死幼犬”。数据是   捕获到信息流中...

     

https://twitter.com/jsnover/status/727902887183966208 ...   https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Information?view=powershell-5.1

请使用定义的输出重定向。

About Redirection

  

示例

# Example 1: Redirect errors and output to a file
dir 'C:\', 'fakepath' 2>&1 > .\dir.log
  

此示例在将成功执行的一项上运行dir,而将在另一项上运行   错误。        它使用2>&1将Error流重定向到Success流,并>将生成的Success流发送到名为dir.log的文件

# Example 2: Send all Success stream data to a file
.\script.ps1 > script.log
  

此命令将所有成功流数据发送到名为script.log的文件

# Example 3: Send Success, Warning, and Error streams to a file


&{
   Write-Warning "hello"
   Write-Error "hello"
   Write-Output "hi"
} 3>&1 2>&1 > P:\Temp\redirection.log
  

此示例说明如何将重定向运算符组合到   取得理想的结果。

     

•3>&1将警告流重定向到成功流。

     

•2>&1将Error流重定向到Success流(该流也将   现在包括所有警告流数据)

     

•>重定向成功流(现在同时包含警告和   错误流)到名为C:\ temp \ redirection.log的文件)

# Example 4: Redirect all streams to a file
.\script.ps1 *> script.log

提供的链接中还有其他输出定义/选项。

相关问题