ssn*_*ssn 5 windows powershell scripting command-line batch-file
我在powershell脚本中有一个foreach循环,在每次迭代期间在shell上打印$ output.有很多输出,shell可以显示的条目数量有限.我希望将输出导出到文本文件.我知道如何在命令行中执行此操作.但是在PowerShell中怎么可能呢?
仅供参考,我使用命令行中的批处理脚本来运行powershell脚本
powershell c:\test.ps1 c:\log.log
Run Code Online (Sandbox Code Playgroud)
Kei*_*ill 12
您始终可以将输出和exe重定向到这样的文件(甚至从cmd.exe):
powershell c:\test.ps1 > c:\test.log
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,在脚本中进行重定向有点痛苦,因为您必须对文件进行大量重定向.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77808 次 |
| 最近记录: |