Search code examples
powershellget-winevent

Get-WinEvent Multiple Servers


I am trying to run the following script

$citrixServers = @('server1', 'server2' , 'server3')
$time = (get-date).AddDays(-16)
foreach ($citrixServer in $citrixServers) {'System' , 'Security' , 'Application'| ForEach-Object {Get-WinEvent -computerName $citrixServer  –FilterHashtable @{logname= $_; starttime=$time}}  | Export-Csv -Path 'd:\scripts\$citrixServer'EventLogs'}

This is creating the first csv file with server1's names and logs but is not moving on to the second servers name. The script does not stop running however it just seems like it stalls out.

Ideally the script will create individual csv files with the event logs for each server. I feel like I am missing something simple here


Solution

  • I don't see anything particularly wrong with your code other than what js2010 mentioned in their comment, there is a syntax error in your path:

    'd:\scripts\$citrixServer'EventLogs'
    

    There is a missing closing quote ' and also variables can't expand in literal strings '...', those quotes should be double quotes "..." so $citrixServer can expand.

    You could use Invoke-Command to parallelize your query though and the LogName key from -FilterHashtable can be LogName = <String[]> so there is no need for the inner loop:

    $citrixServers = @('server1', 'server2' , 'server3')
    
    Invoke-Command -ComputerName $citrixServers {
        Get-WinEvent -FilterHashtable @{
            LogName   = 'System', 'Security', 'Application'
            StartTime = (Get-Date).AddDays(-16)
        } | Select-Object prop1, prop2, ... # <= Can be used here to reduce the amount of memory and CPU usage in local server
    } | Group-Object PSComputerName | ForEach-Object {
        $_.Group | Export-Csv -Path ('d:\scripts\{0}EventLogs' -f $_.Name)
    }