如何同时将字符串输出到变量和控制台

mis*_*kin 10 powershell

在PowerShell中是否有一种简单的方法可以同时将字符串输出到变量和控制台?

我想将我的脚本输出捕获到一个变量,以便我可以在脚本的最后分析它,将其保存到日志文件,并通过电子邮件发送给操作员.

我的意图是有一个变量$ output并向其添加任何输出字符串,并立即输出到控制台

$output="Process started"

$output=+"Doing step 1"
"Doing step 1"

$output=+"Doing step 2"
"Doing step 2"
Run Code Online (Sandbox Code Playgroud)

所以最后我可以将$ 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
Run Code Online (Sandbox Code Playgroud)

man*_*lds 6

有很多方法可以实现您的最终目标:

在你的脚本中只有这样的东西:

"Process started"
<step1>
"Doing step 1"
<step2>
"Doing step 2"
...
Run Code Online (Sandbox Code Playgroud)

然后运行脚本为

.\test.ps1 | Tee-Object -file log.txt
Run Code Online (Sandbox Code Playgroud)

请注意,输出可用于Tee-Object控制台,因此可以在控制台发生时使用.只有在整个脚本运行后才能获得输出.这就是管道在Powershell中的工作方式.对象在它们发生时沿着下游传递.sleep 10在中间插入一个步骤,看看输出是否可用.

此外,您不一定要有另一个脚本(launcher.ps1).您可以在脚本中使用函数,scriptblock等.

其他一些方法:

function test {

"Process started"
sleep 5
"Doing step 1"
sleep 5
"Doing step 2"

}

test | %{$output+=$_;$_}
#use output
write-host -fore blue $output
Run Code Online (Sandbox Code Playgroud)

您可以创建一个过滤器:

$script:output = ""

filter appendOutput {

    $script:output+= $_
    return $_
}

"Process started" | appendOutput
sleep 5
"Doing step 1" | appendOutput
sleep 5
"Doing step 2" | appendOutput
#use output
write-host -fore blue $script:output
Run Code Online (Sandbox Code Playgroud)

可能还有很多方法可以做到这一点.


Sha*_*evy 5

这是一个很好的技巧,将变量赋值括在括号中.您可以在PowerShell语言规范(第7.1.1节分组括号)中找到更多相关信息,可在此处下载:

PS > ($var=1)
1
PS >
Run Code Online (Sandbox Code Playgroud)