将powershell输出导出到文本文件

我在我的powershell脚本中有一个foreach循环,在每次迭代期间在shell上输出$输出。 有很多输出和shell可以显示的条目数量是有限的。 我正在寻找导出输出到一个文本文件。 我知道如何在命令行中做到这一点。 但是如何在PowerShell中实现?

仅供参考,我正在使用命令行中的批处理脚本来运行powershell脚本

powershell c:\test.ps1 c:\log.log 

你总是可以将输出文件重定向到像这样的文件(甚至是来自cmd.exe):

 powershell c:\test.ps1 > c:\test.log 

在PowerShell中,您还可以将单个命令重定向到文件,但在这种情况下,您可能想追加到日志文件而不是覆盖它,例如:

 $logFile = 'c:\temp\test.log' "Executing script $($MyInvocation.MyCommand.Path)" > $logFile foreach ($proc in Get-Process) { $proc.Name >> $logFile } "Another log message here" >> $logFile 

正如你所看到的,在脚本中进行重定向是有点痛苦,因为你必须做大量的重定向到文件。 OTOH,如果你只是想将输出的一部分重定向到文件,那么你有更多的控制权。 另一个选择是使用Write-Host将信息输出到专门用于观察脚本执行结果的人。 请注意, Write-Host输出不能被重定向到文件。

这是从CMD.exe执行的一个例子

 C:\Temp>type test.ps1 $OFS = ', ' "Output from $($MyInvocation.MyCommand.Path). Args are: $args" C:\Temp>powershell.exe -file test.ps1 1 2 ab > test.log C:\Temp>type test.log Setting environment for using Microsoft Visual Studio 2008 Beta2 x64 tools. Output from C:\Temp\test.ps1. Args are: 1, 2, a, b 

那么使用“tee”命令呢?

 C:\ipconfig | tee C:\log.txt