[英]How to get both the output and results to a variable using Write-Host in powershell?
我剛剛在 powershell 上使用Write-Host
時遇到了一個有趣的行為。
我想要做的是從Write-Host
獲取彩色 output 並將結果同時保存在一個變量中。 檢查其他 SO 問題,讓我嘗試以下操作:
$zz = &{
Write-Warning "hello"
Write-Error "hello"
Write-Output "hi"
} 3>&1 2>&1
$zz
#WARNING: hello
#Write-Error: hello
#hi
$zz = &{ Write-Host -ForegroundColor Red "[ERROR]: Package id: ""jaja"" not found!"; } 3>&1 2>&1
# [ERROR]: Package id: "jaja" not found!
$zz
# [nothing]
output 令人驚訝,我無法找到一種方法將 output 保存到變量中,同時還能看到它的顯示,這與使用其他Write-xxx
commandlet 時不同。
問:發生了什么事,我怎樣才能同時顯示 output 並將結果保存到變量中?
REFERENCES:
更新-1
感謝mklement0的更新答案,我還嘗試了以下方法,它幾乎可以滿足我的要求,但不會產生顏色。
Write-Host -ForegroundColor Red "[ERROR]: Package id: ""jaja"" not found!" 6>&1 | Tee-Object -Variable zz
($zz = Write-Host -ForegroundColor Red "[ERROR]: Package id: ""$package"" not found!" 6>&1)
結論似乎是,在使用與從Write-Host
重定向 output 有關的任何內容時,任何着色信息都會丟失。
更新 2
有趣的是,顏色信息仍然“存在”於某處。 按照 mklement0 的建議,我嘗試保存 2 條不同行的顏色信息。 但是然后解析不正確,如下圖。
所以:
$captured = &{ Write-Host -ForegroundColor Red -NoNewline "[ERROR]: some error! " 6>&1; Write-Host -ForegroundColor Green "OKAY" 6>&1 }
我們得到:
正如您鏈接到的答案中所解釋的,您需要重定向6>&1
才能捕獲Write-Host
output (僅適用於 PowerShell v5 及更高版本):
通過6>&1
捕獲Write-Host
output 由一個或多個System.Management.Automation.InformationRecord
實例組成,它們就像字符串一樣打印,即通過它們的.MessageData.Message
屬性值,這是參數的字符串內容( s) 傳遞給Write-Host
。
因此,任何源於使用-ForegroundColor
和-BackgroundColor
參數的着色都不會(直接)通過:
.MessageData.ForegroundColor
和.MessageData.BackgroundColor
屬性中,以及有關-NoNewLine
是否傳遞給Write-Host
的信息,在 Boolean 屬性.MessageData.NoNewLine
相比之下,保留了通過嵌入在原始字符串參數中的ANSI / VT 轉義序列進行着色。
因此,您可以按如下方式重新創建原始着色- 注意再次使用了Write-Host
:
$captured = Write-Host -ForegroundColor Red "[ERROR]: some error" 6>&1
$captured | ForEach-Object {
$messageData = $_.MessageData
$colorArgs = @{}
if (-1 -ne $messageData.ForegroundColor) { $colorArgs.ForegroundColor = $messageData.ForegroundColor }
if (-1 -ne $messageData.BackgroundColor) { $colorArgs.BackgroundColor = $messageData.BackgroundColor }
Write-Host -Object $captured @colorArgs -NoNewline:$messageData.NoNewLine
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.