将变量传递给Get-Winevent

时间:2018-01-10 19:05:10

标签: powershell event-log

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

我已经运行了基本代码,但当我将其转换为函数时,我无法将变量传递给哈希表中的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
}

1 个答案:

答案 0 :(得分:1)

试试这个。从过滤器中删除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
        }