0

I'm trying to build a Get-Winevent command using variables, but I'm having issues with variables inside "built" commands and I've hit the proverbial brick wall. On the last bit of code, if I remove $EventIDQueryAdd and $EntryTypeQueryAdd the command runs without issue. Any assistance would be greatly appreciated! Thanks!

$ArgLastMinutes = 60
$ArgLogName = "Security"
$ArgEntryType = 0 
$ArgEventID = 4625
if ($ArgEventID) { $EventIDQueryAdd="id=$ArgEventID;" }
if ($ArgEntryType) { $EntryTypeQueryAdd="level=$ArgEntryType;" }

write-host "argeventid "$ArgEventID # returns 4625
write-host "argentrytype "$ArgEntryType # returns 1
write-host "eventidqueryadd "$EventIDQueryAdd # returns id=4625; as it should
write-host "entrytypequeryadd "$EntryTypeQueryAdd # returns level=1; as it should
$LogEntries=Get-WinEvent -FilterHashtable @{logname="$ArgLogName"; $EventIDQueryAdd $EntryTypeQueryAdd StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes) }

... <loop through LogEntries> ...

0

You're trying to build a hashtable like a string, it wouldn't work that way. When you say returns id=4625; as it should it's not true, you've got a string here, not a hashtable. For a hashtable you should see this output:

Name    Value
----    -----
Id      4625

Try this:

$ArgLastMinutes = 60
$ArgLogName = 'Security'
$ArgEntryType = 0 
$ArgEventID = 4625

# Create a new hashtable with two keys
$Filter = @{
    LogName = $ArgLogName
    StartTime = (Get-Date).AddMinutes(-$ArgLastMinutes)
}

if($ArgEventID)
{
    # Add new key-value pair to the existing hashtable
    $Filter += @{Id = $ArgEventID}
}

if($ArgEntryType)
{
    # Add new key-value pair to the existing hashtable
    $Filter += @{Level = $ArgEntryType}
}

# Pass the hashtable to the -FilterHashtable parameter
$LogEntries = Get-WinEvent -FilterHashtable $Filter
  • This worked perfectly! Thank you for your assistance! – user433873 Apr 7 '15 at 2:09

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.