在 Get-Winevent 中将变量传递给 hash table 中的 lognam

Pass a variable to the lognam in the hash table in Get-Winevent

我正在尝试将使用 Get-EventLogs 的函数更改为使用 Get-WinEvent。理想情况下,我希望每天可以 运行 拥有一个功能,只需更改几个变量即可扫描不同的日志。

我有基本代码 运行ning,但是当我把它变成一个函数时,我无法将变量传递给散列 table 中的 LogName。我尝试了不同的引号组合,但没有成功。

我收到日志不存在的错误,错误中只有“-”。

function Check-Eventlogs-v2 {
    Param(
        [Parameter(Mandatory=$true)][string]$Type
        #,[string]$Type
        #,[datetime] $date
        ,[int32]$eventtype
        ,[string]$box
    )

    if ($Type -ne '') {
        $servers = Get-Content -LiteralPath "C:\temp\sql_servers3.txt"
        $Date = (Get-Date).AddDays(-1)

        $log = foreach ($box in $servers) {
            Get-WinEvent -Computername $box -LogName = Application -FilterHashTable @{
                Logname   = $Type;
                level     = $eventtype;
                starttime = $Date
            } | Where-Object {
                ($_.Id -ne "2006" -and
                $_.Id -ne "1008" -and
                $_.Id -ne "12289" -and
                $_Logname -eq $Type)
            } | Select-Object @{n='HostName';e={($_.MachineName -split '\.')[0]}}, timecreated, id, message
        }
    } else {
        Write-Warning "'$Type' is not a valid log type."
    }
    return $log
}

试试这个。从过滤器中删除 LogName,并放置一个 ToString 匹配项。您在 Where-Object 中的 LogName 引用中也有拼写错误。

$log = foreach ($box in $servers) {
            Get-WinEvent -Computername $box -LogName = Application -FilterHashTable @{
                level     = $eventtype;
                starttime = $Date
            } | Where-Object {
                ($_.Id -ne "2006" -and
                $_.Id -ne "1008" -and
                $_.Id -ne "12289" -and
                $_.Logname.ToString() -eq $Type)
            } | Select-Object @{n='HostName';e={($_.MachineName -split '\.')[0]}}, timecreated, id, message
        }