Mar*_*tin 185 powershell scripting stdout
我有一个PowerShell脚本,我想将输出重定向到一个文件.问题是我无法改变调用此脚本的方式.所以我做不到:
.\MyScript.ps1 > output.txt
Run Code Online (Sandbox Code Playgroud)
如何在执行期间重定向PowerShell脚本的输出?
Bra*_*tch 178
也许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"
Run Code Online (Sandbox Code Playgroud)
Nat*_*ley 47
微软已在Powershell的Connections网站(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
Run Code Online (Sandbox Code Playgroud)
有关详细信息和示例,请参阅"about_Redirection"帮助文章.
help about_Redirection
Run Code Online (Sandbox Code Playgroud)
小智 33
使用:
Write "Stuff to write" | Out-File Outputfile.txt -Append
Run Code Online (Sandbox Code Playgroud)
zda*_*dan 24
一种可能的解决方案,如果您的情况允许:
创建一个新的MyScript.ps1,如下所示:
.\ TheRealMyScript.ps1> output.txt
mpl*_*ork 24
我认为你可以修改MyScript.ps1.然后尝试改变它:
$(
Here is your current script
) *>&1 > output.txt
Run Code Online (Sandbox Code Playgroud)
我刚刚尝试使用PowerShell 3.您可以使用所有重定向选项,如Nathan Hartley的回答.
And*_*der 17
您可能需要查看cmdlet Tee-Object.您可以将输出传输到Tee,它将写入管道以及文件
sui*_*eng 15
powershell ".\MyScript.ps1" > test.log
Run Code Online (Sandbox Code Playgroud)
son*_*njz 11
如果要将所有输出直接重定向到文件,请尝试使用*>>:
# 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 ;
Run Code Online (Sandbox Code Playgroud)
由于这是直接重定向到文件,因此它不会输出到控制台(通常很有帮助).如果您需要控制台输出,请将所有输出组合在一起*&>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 ;
Run Code Online (Sandbox Code Playgroud)
我相信PowerShell 3.0或更高版本支持这些技术; 我在PowerShell 5.0上测试.
小智 8
如果您想从命令行执行此操作而不是内置到脚本本身中,请使用:
.\myscript.ps1 | Out-File c:\output.csv
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
540359 次 |
| 最近记录: |