PowerShell splatting合并到一个哈希表

PowerShell splatting merging to one hashtable

这段代码完成了我想要它做的事情:

$EventParams = @{
    LogName = $LogName
    Source  = $Source
}
$EventInfoParams = $EventParams + @{
    EntryType = 'Information'
    EventID   = '0'
}
$EventWarnParams = $EventParams + @{
    EntryType = 'Warning'
    EventID   = '1'
}
$EventErrorParams = $EventParams + @{
    EntryType = 'Error'
    EventID   = '2'
}

this blog 上,我发现可能有 nicer/cleaner 种方法可以将其写入一个大哈希表。所以我尝试了以下方法:

$EventParams = @{
    LogName = $LogName
    Source  = $Source
    Info = @{
        EntryType = 'Information'
        EventID   = '0'
    }
    Warn = @{
        EntryType = 'Warning'
        EventID   = '1'
    }
    Error = @{
        EntryType = 'Error'
        EventID   = '2'
    }
}

$EventParams.Info

这很好用,除了我无法在不复制数据的情况下从每个单个哈希表中的第一个示例 $EventParams 中获取变量。有没有办法把所有的东西都放在一个大 hashable 中?

据我了解你的问题,你想在同一个哈希表中引用 LogNameSource?我怀疑这是可能的。

但是,您可以使用函数:

function Get-EventParams 
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true,Position=0)]
        [string]$LogName,

        [Parameter(Mandatory=$true,Position=1)]
        [string]$Source,

        [Parameter(Mandatory=$true,Position=2, ParameterSetName='info')]
        [switch]$Info,

        [Parameter(Mandatory=$true,Position=2, ParameterSetName='warn')]
        [switch]$Warn,

        [Parameter(Mandatory=$true,Position=2, ParameterSetName='error')]
        [switch]$Error

    )
        @{
            LogName = $LogName
            Source  = $Source
        }

        if ($Info)
        {
            @{
                EntryType = 'Information'
                EventID   = '0'
            }
        }
        if ($Warn)
        {
            @{
                EntryType = 'Warning'
                EventID   = '1'
            }
        }

        if ($Error)
        {
            @{
                EntryType = 'Error'
                EventID   = '2'
            }
        }
}

现在您可以获得所需的哈希表,例如:

Get-EventParams -LogName "Azure" -Source "Application" -Info

为方便起见,您还可以为 LogNameSoruce 参数定义一个 ValidateSet

通常,您会将给定脚本中的所有或大部分事件写入公共日志和源。如果您想避免代码重复,您可以在脚本开头使用 $PSDefaultParameters 为将从脚本编写的所有事件设置一次:

#Set event loggin defaults
$PSDefaultParameterValues = 
 $PSDefaultParameterValues.Clone() + @{
    'Write-Eventlog:LogName' = $LogName
    'Write-Eventlog:Source' = $Source
   }

克隆它会在脚本中创建一个新副本,继承父级或全局范围中已经设置的任何默认值,而不更改该范围中的散列 table。新的 $PSDefaultParameterValues 将在脚本完成时被释放,并且设置将恢复为父范围内的任何设置。

如果您需要写入脚本中某处的其他日志或源,您可以通过为该事件指定日志名称和源来实现,覆盖默认值。