简体   繁体   English

PowerShell 将主机 append 写入文本文件

[英]PowerShell Write-Host append to a text file

Im new in PowerShell and working on a script more than 500 lines.我是 PowerShell 的新手,正在编写超过 500 行的脚本。 I use the write-host command often.我经常使用write-host命令。 And now Im working on doing the Logging part.现在我正在做 Logging 部分。 Also, sorry for the bad English.另外,对不起英语不好。

I want the script to save every write-host command in a.txt, append and still let the write-host command output passthrough to the Shell output. I want the script to save every write-host command in a.txt, append and still let the write-host command output passthrough to the Shell output.

Things I tried:我尝试过的事情:

&{
# the script 
} *>> $logPath
Start-Transcript -Path $logPath
# the script 
Stop-Transcript 

It works but its not letting the output passthrough.它可以工作,但不允许 output 通过。

One way of doing that would be to be to use Out-File cmdlet by wrapping your whole script like this:-一种方法是通过像这样包装整个脚本来使用Out-File cmdlet:-

@(
Write-Output "######### Loop 1 #########"
foreach ($i in (1..5))
{
    Write-Output $i "--> Loop1"
}

Write-Output "######### Loop 2 #########"
foreach ($i in (6..11))
{
    Write-Output $i "--> Loop2"
}

Write-Output "######### Loop 3 #########"
foreach ($i in (12..15))
{
    Write-Output $i "--> Loop3"
}
) | Out-file $env:USERPROFILE\Desktop\Output.txt -width 50

Use Write-Output instead of Write-Host as Write-Host writes to the console itself where as Write-Output sends the output to the pipeline.使用Write-Output而不是Write-Host作为Write-Host写入控制台本身,而Write-Output将 output 发送到管道。 See here for details.有关详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM