【发布时间】:2019-07-04 19:00:37
【问题描述】:
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
【问题讨论】:
标签: powershell