McVitas
McVitas

Reputation: 302

PowerShell get-winevent via invoke-command does not like array

explain me this mystery: on a server I can do:

$lastdate=(get-date).adddays(-19)
get-winevent -FilterHashTable @{LogName='setup'; StartTime=$lastdate;id=@(2,3,4)}|sort timecreated

and it shows events but if I try to do it via invoke-command from another server in a domain it does not work with parameter id=$eventids and I get no events

$lastdate=(get-date).adddays(-19)
$eventids=@(2,3,4)
$evts=invoke-command -cn $hostname -argumentlist $lastdate,$eventids -scriptblock {
 param($lastdate,$eventids)
 Get-WinEvent -FilterHashTable @{LogName='setup'; StartTime=$lastdate;id=$eventids}|sort timecreated
}

$evts: No events were found that match the specified selection criteria.

However if I remove id=$eventids or replace $eventids with @(2,3,4) like in the first example it works! Why is that? The variable $eventids is passed fine, I can add it in the scriptblock and it then appears in $evts as a result of invoke-command

Upvotes: 0

Views: 488

Answers (2)

js2010
js2010

Reputation: 27423

You're not using "invoke-command -argumentlist" to pass in the local variables. (EDIT: I see it now) But even then invoke-command has a problem with arrays [with one argument anyway]. I would define the variables inside the invoke-command scriptblock. @() is not necessary to create arrays.

I've seen this before. I just made a bug report: get-winevent inside invoke-command can't handle arrays inside filterhashtable

Upvotes: 1

Theo
Theo

Reputation: 61068

I honestly have no idea why, but if I do a Write-Host or Start-Sleep -Milliseconds 1 before the Get-WinEvent call and do a cast to [array] or [int[]] on the $eventids variable, it seems to work just fine.

$lastdate = (Get-Date).adddays(-19)
$eventids = 2,3,4
$evts = Invoke-Command -ComputerName $hostname -ArgumentList $lastdate, $eventids -ScriptBlock {
    param($lastdate, $eventids)
    # either Write-Host or Start-Sleep -Milliseconds 1 seem to add enough delay
    Start-Sleep -Milliseconds 1
    # without the cast [array] or [int[]] you'll still get the error message
    # "No events were found that match the specified selection criteria."
    Get-WinEvent -FilterHashTable @{LogName='setup'; StartTime=$lastdate;id=[int[]]$eventids} | Sort-Object timecreated
}
$evts

You can also do the cast in the param block:

param($lastdate, [int[]]$eventids)

instead of doing that in the hashtable.

I'm using PowerShell 5.1.18362.752

Upvotes: 1

Related Questions