0

我正在尝试以最短的方式Write-Host发送消息并将其保存到变量中。

目前我的代码如下所示:

Write-Host "Branch with name $branch_name already exists!`nNew branch has not been created."
$message = "Branch with name $branch_name already exists!`nNew branch has not been created."

当然它有效。我做了一个特殊的函数来压缩这个:

function Write-Host-And-Save([string]$message)
{
Write-Host $message
return $message
}

$message = Write-Host-And-Save "Branch with name $branch_name already exists!`nNew branch has not been created."

但是它没有在屏幕上产生任何输出。更重要的是,我认为必须有比新功能更好的解决方案来做到这一点。我试图找到一个。不成功。

Write-Host "Branch with name $branch_name already exists!`nNew branch has not been created." >> $message
Write-Host "Branch with name $branch_name already exists!`nNew branch has not been created." > $message
Write-Host "Branch with name $branch_name already exists!`nNew branch has not been created." -OutVariable $message

有什么方法可以使该脚本短路吗?

4

2 回答 2

3

在 PowerShell 5+ 上,您可以通过使用带有 common 参数的Write-Host来实现所需的行为-InformationVariable。以下示例将字符串值存储在$message.

Write-Host "Branch with name $branch_name already exists" -InformationVariable message

解释:

从 PowerShell 5 开始,Write-Host成为Write-Information. 这意味着Write-Host写入信息流。鉴于这种行为,您可以使用-InformationVariable Common Parameter将其输出存储到变量中。


或者,您可以使用成功流和 common 参数通过Write-Output获得类似的结果-OutVariable

Write-Output "Branch with name $branch_name already exists" -OutVariable message

通常,我会赞成使用Write-Outputover Write-Host。它具有更同步的行为并使用成功流,这是您打算在此处使用的。Write-Host确实提供了轻松着色控制台输出的能力。

于 2019-12-19T12:49:20.890 回答
2

您可以使用Tee-Objectwhich 将其输入转发到管道中,也可以将其保存到变量(或文件,如果需要):

"Some message" | Tee-Object -Variable message | Write-Host

您也可以从以下开始Write-Host

Write-Host "Some message" 6>&1 | Tee-Object -Variable message

将写入(从 Powershell 5.0 开始)6>&1的信息流 (6) 重定向到标准输出流 (1)。Write-Host您甚至可以使用它*>&1来捕获所有流。

在这种情况下,最终输出最终会出现在常规输出流中,因此它不能准确回答您的问题。这只是一个示例,您可以如何使用Tee-Object将输出捕获到变量的一般用例,同时仍将其输出到控制台(或管道下方的任何 cmdlet)。

于 2019-12-19T12:47:25.673 回答