I am trying to Write-Host
message and save it to a variable in shortest possible way.
Currently my code looks like so:
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."
And of course it works. I made a special function to compress this:
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."
However it didn't make any output on screen. What is more I think there must be a better solution than new function to do it. And I tried to find one. Unsuccessfully.
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
Is there any way to short-circuit that script?
On PowerShell 5+, you can achieve the desired behavior by utilizing Write-Host with the common parameter -InformationVariable
. The following example stores the string value in $message
.
Write-Host "Branch with name $branch_name already exists" -InformationVariable message
Explanation:
Starting with PowerShell 5, Write-Host
became a wrapper for Write-Information
. This means Write-Host
writes to the information stream. Given that behavior, you can store its output into a variable using the -InformationVariable
Common Parameter.
Alternatively, you can achieve similar results with Write-Output using the success stream and the common parameter -OutVariable
.
Write-Output "Branch with name $branch_name already exists" -OutVariable message
Typically, I would be in favor of using Write-Output
over Write-Host
. It has a more synchronous behavior and uses the success stream, which is what you are intending to use here. Write-Host
does provide the ability to easily color your console output though.