简体   繁体   English

将powershell输出导出到文本文件

[英]Exporting powershell output to text file

I have a foreach loop inside my powershell script with prints $output on the shell during each iteration. 我在powershell脚本中有一个foreach循环,在每次迭代期间在shell上打印$ output。 There are lot many outputs and the number of entries that the shell can display is limited. 有很多输出,shell可以显示的条目数量有限。 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中怎么可能呢?

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 

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 eg: 在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. OTOH,如果您只想将部分输出重定向到文件,那么您可以通过这种方式获得更多控制权。 Another option is to use Write-Host to output info to the console meant for someone observing the results of the script execution. 另一种选择是使用Write-Host将信息输出到控制台,以供观察脚本执行结果的人使用。 Note that Write-Host output cannot be redirected to file. 请注意, 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

怎么样使用'tee'命令

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

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

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