Search code examples
eventspowershellevent-viewer

Powershell: function parameters


I'm building a powershell function so i can query multiple computers event logs. Ive copied the code below that i need help with. If I don't send an eventID, I want the script to find all event ID's, how can i achieve this?

#this would be the parameter part of the script
[String]$ComputerName = $env:COMPUTERNAME#Current computer 
[String[]]$EventLogNames=@("Application","System")#Main eventlogs 
[int[]]$EventIds = 1 #Event Ids 
[System.DateTime[]]$EventStartDate = (((Get-Date).addDays(-2)).date)#date 10 days ago 
[System.DateTime[]]$EventEndTime = (Get-Date)#date 10 days ago 

#This fits in the process section
$EventCritea = @{logname = $EventLogNames; StartTime=$EventStartDate; EndTime=$EventEndTime; ID=$EventIds}
Get-WinEvent -ComputerName $ComputerName -FilterHashTable $EventCritea  -ErrorAction SilentlyContinue

Solution

  • First, your other question fixes the types of $EventStartDate and $EventEndTime.

    For this question: build the hashtable incrementally:

    $filter = @{logname = $EventLogNames; StartTime=$EventStartDate; EndTime=$EventEndTime}
    
    if ($EventIds -ne $null -and $EventIds.Length -gt 0) {
      $filter.ID=$EventIds
    }
    
    Get-WinEvent -ComputerName $ComputerName -FilterHashTable $filter #...