6

我的 powershell 脚本中有一个 foreach 循环,每次迭代期间都会在 shell 上打印 $output 。有很多输出,shell 可以显示的条目数量是有限的。我希望将输出导出到文本文件。我知道如何在命令行中做到这一点。但是在powershell中怎么可能呢?

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

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

2 回答 2

14

您始终可以将输出的 exe 重定向到这样的文件(即使来自 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 a b > 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
于 2012-04-26T19:41:44.390 回答
5

使用 'tee' 命令怎么样

C:\ipconfig | tee C:\log.txt
于 2013-08-21T23:56:40.777 回答