windows 将powershell输出导出到文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10340007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:29:01  来源:igfitidea点击:

Exporting powershell output to text file

windowspowershellcommand-linescriptingbatch-file

提问by ssn

I have a foreach loop inside my powershell script with prints $output on the shell during each iteration. There are lot many outputs and the number of entries that the shell can display is limited. I am looking to export the output to a text file. I know how to do it in command line. How is it possible in a powershell though?

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

FYI, I am using a batch script from the command line to run the powershell script as

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

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

回答by Keith Hill

You can always redirect the output an exe to a file like so (even from cmd.exe):

您始终可以将 exe 的输出重定向到这样的文件(甚至来自 cmd.exe):

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

Within PowerShell, you can also redirect individual commands to file but in those cases you probably want to append to the log file rather than overwrite it e.g.:

在 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

As you can see, doing the redirection within the script is a bit of a pain because you have to do lots of redirects to file. OTOH, if you only want to redirect part of the output to file then you have more control this way. Another option is to use Write-Hostto output info to the console meant for someone observing the results of the script execution. Note that Write-Hostoutput cannot be redirected to file.

如您所见,在脚本中进行重定向有点麻烦,因为您必须对文件进行大量重定向。OTOH,如果您只想将部分输出重定向到文件,那么您可以通过这种方式进行更多控制。另一种选择是用于Write-Host将信息输出到控制台,供观察脚本执行结果的人使用。请注意,Write-Host输出不能重定向到文件。

This is an example executed from CMD.exe

这是从 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

回答by rojomisin

what about using the 'tee' command

使用'tee'命令怎么样

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