在 PowerShell 中,是否有一种简单的方法可以同时将字符串输出到变量和控制台?
我想捕获脚本的输出并保存到变量中,以便在脚本结束时分析它、将其保存到日志文件并通过电子邮件发送给操作员。
我的意图是创建一个名为 $output 的变量,并将任何输出字符串添加到其中,同时立即输出到控制台,类似于:
$output="Process started"
$output=+"Doing step 1"
"Doing step 1"
$output=+"Doing step 2"
"Doing step 2"
最终,我可以将$output保存到日志文件中、通过电子邮件发送并解析它。
我尝试使用tee-object来实现这个目的,但不幸的是,它会重写我的$output变量,而不是将字符串追加到它后面。
更新 这是我决定采用的最终解决方案-感谢manojlds!
$script:output = ""
filter mylog {
$script:output+= $_+"`n"
return $_
}
"doing step {0}" -f 1 | mylog
"doing step {0}" -f 2 | mylog
"doing step {0}" -f 3 | mylog
#in the end of the script
$script:output
.\test.ps1 | Tee-Object -file log.txt
- 如果你这样做,你会在控制台上看到输出的实时情况。在上述脚本字符串之间添加sleep 10
并查看。同时请查看我的更新答案。 - manojlds