我有一个带有一系列Invoke-Command语句的脚本,每个语句都有代码写到文件。我可以暂时改变Out-Default的行为并稍微清理我的脚本吗?
... | Out-File $LogFile -append
[编辑]这是在Powershell 2.0上
你能?是。
filter Out-Default{ $_ | Out-File 'C:\logfile.txt' -append }
现在,默认情况下,所有输出都将转到日志文件。通过删除临时定义
dir function:\Out-Default | del
但这非常hacky,非显而易见,难以维护,所以我不推荐它。最好定义一个简单的专用日志记录功能,这样您只需要将| log
添加到脚本的相关行。获得一些显而易见的理解,调试和更改的额外代码要比添加hacks只是为了“简化”代码要好得多。
我不会改变Out-Default
的工作方式,如果你有PowerShell 3.0,你可以为Out-File
设置默认参数值,这样做不需要你在命令行上指定它们:
$PSDefaultParameterValues['Out-File:FilePath'] = $LogFile
$PSDefaultParameterValues['Out-File:Append'] = $true
... | Out-File
来自“Powershell Cookbook”,2013年:
<#
.SYNOPSIS
Adds a new Out-Default command wrapper to store up to 500 elements from
the previous command. This wrapper stores output in the $ll variable.
#>
Set-StrictMode -Version 3
New-CommandWrapper Out-Default `
-Begin {
$cachedOutput = New-Object System.Collections.ArrayList
} `
-Process {
if($_ -ne $null) { $null = $cachedOutput.Add($_) }
while($cachedOutput.Count -gt 500) { $cachedOutput.RemoveAt(0) }
} `
-End {
$uniqueOutput = $cachedOutput | Foreach-Object {
$_.GetType().FullName } | Select -Unique
$containsInterestingTypes = ($uniqueOutput -notcontains `
"System.Management.Automation.ErrorRecord") -and
($uniqueOutput -notlike `
"Microsoft.PowerShell.Commands.Internal.Format.*")
if(($cachedOutput.Count -gt 0) -and $containsInterestingTypes)
{
$GLOBAL:ll = $cachedOutput | % { $_ }
}
}