gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:27:57 26 4
gpt4 key购买 nike

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

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

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

最佳答案

您始终可以将 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

关于windows - 将 powershell 输出导出到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10340007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com