I'm trying to change a function using Get-EventLogs
to use Get-WinEvent
. Ideally I would like to have one function I can run daily and simply change a few variables to scan different logs.
I have the basic code running, but when I turned it into a function I cannot pass a variable to the LogName in the hash table. I try different combinations of quotes, but no luck.
I get errors that the log doesn't exist with only "-" being in the error.
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
}
Try this. Got rid of LogName from the filter, and put a ToString match. You also had a typo in the LogName reference in Where-Object.
$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
}