我正在尝试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
有什么办法可以使该脚本短路?
答案 0 :(得分:3)
在PowerShell 5+上,您可以通过将Write-Host与公用参数list1 = [("Joe Black", "married", "happy"),("Mili Cis", "unmarried" , "happy"),("Gary Oldman", "married", "unhappy")]
list2 = ["Joe Black","Gary Oldman"]
list3= []
for name in list2:
for item in list1:
for sub_item in item:
if name == sub_item:
list3.append(item)
print(list3)
一起使用来实现所需的行为。以下示例将字符串值存储在-InformationVariable
中。
$message
说明:
从PowerShell 5开始,Write-Host "Branch with name $branch_name already exists" -InformationVariable message
成为Write-Host
的包装器。这意味着Write-Information
写入信息流。在这种情况下,您可以使用Write-Host
Common Parameter将其输出存储到变量中。
或者,您可以使用成功流和公用参数-InformationVariable
,使用Write-Output获得类似的结果。
-OutVariable
通常,我倾向于使用Write-Output "Branch with name $branch_name already exists" -OutVariable message
而不是Write-Output
。它具有更同步的行为,并使用成功流,这是您打算在此处使用的。 Write-Host
确实提供了轻松为控制台输出着色的功能。
答案 1 :(得分:2)
您可以使用Tee-Object
来将其输入转发到管道中,以及将其保存到变量(或所需的文件)中:
"Some message" | Tee-Object -Variable message | Write-Host
您也可以以Write-Host
开头:
Write-Host "Some message" 6>&1 | Tee-Object -Variable message
6>&1
将Write-Host
写入的信息流(6)(从Powershell 5.0开始)重定向到标准输出流(1)。您甚至可以使用*>&1
捕获所有流。
在这种情况下,最终输出最终将出现在常规输出流中,因此它无法完全回答您的问题。只是一个示例,如何使用Tee-Object
作为捕获变量输出并将其输出到控制台(或更进一步的cmdlet)的一般用例。