你能改变脚本的Out-Default行为吗?

问题描述 投票:1回答:3

我有一个带有一系列Invoke-Command语句的脚本,每个语句都有代码写到文件。我可以暂时改变Out-Default的行为并稍微清理我的脚本吗?

... | Out-File $LogFile -append

[编辑]这是在Powershell 2.0上

powershell powershell-v2.0
3个回答
5
投票

你能?是。

filter Out-Default{ $_ | Out-File 'C:\logfile.txt' -append }

现在,默认情况下,所有输出都将转到日志文件。通过删除临时定义

dir function:\Out-Default | del

但这非常hacky,非显而易见,难以维护,所以我不推荐它。最好定义一个简单的专用日志记录功能,这样您只需要将| log添加到脚本的相关行。获得一些显而易见的理解,调试和更改的额外代码要比添加hacks只是为了“简化”代码要好得多。


5
投票

我不会改变Out-Default的工作方式,如果你有PowerShell 3.0,你可以为Out-File设置默认参数值,这样做不需要你在命令行上指定它们:

$PSDefaultParameterValues['Out-File:FilePath'] = $LogFile
$PSDefaultParameterValues['Out-File:Append'] = $true


... | Out-File

0
投票

来自“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 | % { $_ }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.