我有一个 PowerShell 脚本,我想将其输出重定向到一个文件。问题是我无法更改调用此脚本的方式。所以我不能这样做:
.\MyScript.ps1 > output.txt
如何在执行期间重定向 PowerShell 脚本的输出?
也许 Start-Transcript
对您有用。如果它已经在运行,首先停止它,然后启动它,完成后停止它。
$ErrorActionPreference="SilentlyContinue" Stop-Transcript | out-null $ErrorActionPreference = "Continue" Start-Transcript -path C:\output.txt -append # Do some stuff Stop-Transcript
您也可以在处理内容时运行它,并让它保存您的命令行会话以供以后参考。
如果您想在尝试停止未转录的成绩单时完全抑制错误,您可以这样做:
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"
Microsoft announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) 在 3.0 版中已扩展重定向作为解决此问题的方法。
In PowerShell 3.0, we've extended output redirection to include the following streams:
Pipeline (1)
Error (2)
Warning (3)
Verbose (4)
Debug (5)
All (*)
We still use the same operators
> Redirect to a file and replace contents
>> Redirect to a file and append to existing content
>&1 Merge with pipeline output
有关详细信息和示例,请参阅“about_Redirection”帮助文章。
help about_Redirection
利用:
Write "Stuff to write" | Out-File Outputfile.txt -Append
我认为您可以修改 MyScript.ps1
。然后尝试像这样更改它:
$(
Here is your current script
) *>&1 > output.txt
我刚刚使用 PowerShell 3 进行了尝试。您可以使用 Nathan Hartley's answer 中的所有重定向选项。
*>&1 | Out-File $log -Encoding ascii -Append -Width 132
但如果您需要精确控制输出,Powershell 真的很难看。
powershell ".\MyScript.ps1" > test.log
如果您的情况允许,一种可能的解决方案:
将 MyScript.ps1 重命名为 TheRealMyScript.ps1 创建一个新的 MyScript.ps1,如下所示: .\TheRealMyScript.ps1 > output.txt
如果您想要将所有输出直接重定向到文件,请尝试使用 *>>
:
# You'll receive standard output for the first command, and an error from the second command.
mkdir c:\temp -force *>> c:\my.log ;
mkdir c:\temp *>> c:\my.log ;
由于这是对文件的直接重定向,因此不会输出到控制台(通常很有帮助)。如果您需要控制台输出,请将所有输出与 *&>1
组合,然后使用 Tee-Object
管道:
mkdir c:\temp -force *>&1 | Tee-Object -Append -FilePath c:\my.log ;
mkdir c:\temp *>&1 | Tee-Object -Append -FilePath c:\my.log ;
# Shorter aliased version
mkdir c:\temp *>&1 | tee -Append c:\my.log ;
我相信 PowerShell 3.0 或更高版本支持这些技术;我正在 PowerShell 5.0 上进行测试。
您可能需要查看 cmdlet Tee-Object。您可以将输出通过管道传输到 Tee,它将写入管道以及文件
如果您想从命令行执行它而不是内置到脚本本身中,请使用:
.\myscript.ps1 | Out-File c:\output.csv
要将其嵌入到您的脚本中,您可以这样做:
Write-Output $server.name | Out-File '(Your Path)\Servers.txt' -Append
这应该够了吧。