【发布时间】:2011-04-07 23:10:34
【问题描述】:
我有一个正在调试的 PowerShell 脚本,并且想将所有 Write-Host 语句重定向到一个文件。有没有简单的方法可以做到这一点?
【问题讨论】:
-
我刚刚发现 Start-Transcript 将所有内容从您的窗口输出到一个文件,但是当我将它添加到 ps1 文件时似乎还没有工作。
标签: powershell
我有一个正在调试的 PowerShell 脚本,并且想将所有 Write-Host 语句重定向到一个文件。有没有简单的方法可以做到这一点?
【问题讨论】:
标签: powershell
在 PowerShell 4.0 之前,
Write-Host将对象发送到主机。它不返回任何对象。从 PowerShell 5.0 和更高版本开始,
Write-Host是Write-Information的包装器,它允许输出到信息流并使用6>> file_name将其重定向。
http://technet.microsoft.com/en-us/library/hh849877.aspx
但是,如果您有很多 Write-Host 语句,请将它们全部替换为 Write-Log,这样您就可以决定是输出到控制台、文件还是事件日志,还是全部三个。
也检查一下:
Add-Content>, >>, 2>, 2>, 2>&1
Write-LogStart-Transcript。【讨论】:
write-host "test" > c:\temp\out.txt 我在文件中什么也得不到。输出写入控制台
您可以为Write-Host 创建一个代理函数,它将对象发送到标准输出流,而不仅仅是打印它们。我为此目的编写了以下 cmdlet。它将动态创建一个代理,该代理仅在当前管道的持续时间内持续。
完整的文章在我的博客here 上,但我已经包含了下面的代码。使用-Quiet 开关抑制控制台写入。
用法:
PS> .\SomeScriptWithWriteHost.ps1 | Select-WriteHost | out-file .\data.log # Pipeline usage
PS> Select-WriteHost { .\SomeScriptWithWriteHost.ps1 } | out-file .\data.log # Scriptblock usage (safer)
function Select-WriteHost
{
[CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
param(
[Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')]
[object] $InputObject,
[Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)]
[ScriptBlock] $ScriptBlock,
[switch] $Quiet
)
begin
{
function Cleanup
{
# Clear out our proxy version of write-host
remove-item function:\write-host -ea 0
}
function ReplaceWriteHost([switch] $Quiet, [string] $Scope)
{
# Create a proxy for write-host
$metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host')
$proxy = [System.Management.Automation.ProxyCommand]::create($metaData)
# Change its behavior
$content = if($quiet)
{
# In quiet mode, whack the entire function body,
# simply pass input directly to the pipeline
$proxy -replace '(?s)\bbegin\b.+', '$Object'
}
else
{
# In noisy mode, pass input to the pipeline, but allow
# real Write-Host to process as well
$proxy -replace '(\$steppablePipeline\.Process)', '$Object; $1'
}
# Load our version into the specified scope
Invoke-Expression "function ${scope}:Write-Host { $content }"
}
Cleanup
# If we are running at the end of a pipeline, we need
# to immediately inject our version into global
# scope, so that everybody else in the pipeline
# uses it. This works great, but it is dangerous
# if we don't clean up properly.
if($pscmdlet.ParameterSetName -eq 'FromPipeline')
{
ReplaceWriteHost -Quiet:$quiet -Scope 'global'
}
}
process
{
# If a scriptblock was passed to us, then we can declare
# our version as local scope and let the runtime take
# it out of scope for us. It is much safer, but it
# won't work in the pipeline scenario.
#
# The scriptblock will inherit our version automatically
# as it's in a child scope.
if($pscmdlet.ParameterSetName -eq 'FromScriptBlock')
{
. ReplaceWriteHost -Quiet:$quiet -Scope 'local'
& $scriptblock
}
else
{
# In a pipeline scenario, just pass input along
$InputObject
}
}
end
{
Cleanup
}
}
【讨论】:
您可以在辅助 PowerShell shell 中运行脚本并捕获如下输出:
powershell -File 'Your-Script.ps1' > output.log
这对我有用。
【讨论】:
使用重定向将导致Write-Host 挂起。这是因为 Write-Host 处理特定于当前正在使用的终端的各种格式问题。如果您只想让脚本能够灵活地正常输出(默认为 shell,具有>、2> 等功能),请使用Write-Output。
否则,如果您真的想捕捉当前终端的特性,Start-Transcript 是一个不错的起点。否则,您将不得不手动测试或编写一些复杂的测试套件。
【讨论】:
这适用于我几天前编写的第一个 PowerShell 脚本:
function logMsg($msg)
{
Write-Output $msg
Write-Host $msg
}
在脚本中的使用:
logMsg("My error message")
logMsg("My info message")
PowerShell 脚本执行调用:
ps> .\myFirstScript.ps1 >> testOutputFile.txt
这并不完全是对这个问题的回答,但它可能会帮助那些试图同时实现登录到控制台和输出到某个日志文件的人,做我在这里达到的 :)
【讨论】:
尝试在尖括号> 前添加星号* 以重定向所有流:
powershell -File Your-Script.ps1
*> output.log
当请求流重定向时,如果没有指定特定流,则默认情况下仅重定向 Success Stream(1>)。 Write-Host 是Write-Information 的别名,它写入Information Stream (6>)。要重定向所有流,请使用*>。
Powershell-7.1支持多个输出流的重定向:
Write-Output
Write-Error
Write-Warning
Write-Verbose
Write-Debug
Write-Information
【讨论】:
定义一个名为 Write-Host 的函数。让它写入文件。如果某些调用使用一组奇怪的参数,您可能会遇到一些麻烦。此外,这仅适用于非 Snapin 限定的调用。
【讨论】:
如果您只有几个 Write-Host 语句,您可以使用 "6>>" 重定向器操作符到一个文件:
Write-Host "Your message." 6>> file_path_or_file_name
这是微软提供的"Example 5: Suppress output from Write-Host",相应修改为about_Operators。
【讨论】:
我刚刚在脚本顶部添加了Start-Transcript,在底部添加了Stop-Transcript。
输出文件原本打算命名为<folder where script resides>-<datestamp>.rtf,但由于某种原因,跟踪文件被放到了我没想到的地方——桌面!
【讨论】:
如果您希望将消息保存在文件中,则不应使用 Write-Host。它仅用于写入主机。
相反,您应该使用日志记录模块,或 Set/Add-Content。
【讨论】:
我发现处理此问题的最佳方法是拥有一个日志功能,该功能将检测是否存在主机 UI 并采取相应措施。当脚本在交互模式下执行时,它将在主机 UI 中显示详细信息,但当它通过 WinRM 或在非交互模式下运行时,它将退回到Write-Output,以便您可以使用 @ 捕获它987654326@或*>redirection operators
function Log-Info ($msg, $color = "Blue") {
if($host.UI.RawUI.ForegroundColor -ne $null) {
Write-Host "`n[$([datetime]::Now.ToLongTimeString())] $msg" -ForegroundColor $color -BackgroundColor "Gray"
} else {
Write-Output "`r`n[$([datetime]::Now.ToLongTimeString())] $msg"
}
}
如果您想使用Write-Host 着色捕获完整输出,可以使用Get-ConsoleAsHtml.ps1 脚本将主机的滚动缓冲区导出到HTML 或RTF 文件。
【讨论】:
使用Write-Output 而不是Write-Host,并将其重定向到这样的文件:
Deploy.ps1 > mylog.log or Write-Output "Hello World!" > mylog.log
【讨论】:
尝试使用Write-Output 而不是Write-Host。
输出沿着管道传输,但如果这是管道的末端,它会进入控制台。
> Write-Output "test"
test
> Write-Output "test" > foo.txt
> Get-Content foo.txt
test
【讨论】: