rossboulet
rossboulet

Reputation: 13

Powershell calculated value in where-object clause

I'm trying to make my Powershell script as simple as possible. But I'm having trouble with the where-object clause. The following code does what I want:

# define calculated variables 
$mytime = @{label="Time";expression={$_.timegenerated}}
$myeid  = @{l="EID";e={$_.instanceid -band 0xffff}}
$mymsg  = @{l="Msg 1st 20";e={$_.message.substring(0,20)}}

# get data
Get-Eventlog system |
  where-object { ( $_.instanceid -band 0xffff ) -eq 6005} |
  select-object -first 10 instanceid,
    $mytime,
    $myeid,
    $mymsg

But I was thinking it would be more simple if the where-object could use the $myeid

...
  where-object { $myeid -eq 6005} |
...

But I don't get any results when I use this where-object clause. I've tried various combinations of wrapping it in braces, parentheses, and $(...) with no luck. What am I missing?

And later, I found there was already a script property to extract the EventID, but I'm still wondering why this doesn't work.

Upvotes: 1

Views: 497

Answers (1)

js2010
js2010

Reputation: 27626

$myeid is just a hashtable with a string and a scriptblock. Select-object is programmed to make use of it. Somehow you'd have to run the scriptblock $myeid.e to get a value out of it. This comes close to your original code. Without the parentheses, "-eq 6005" gets ignored. I added 0xf0000 to 6005.

$myeid  = @{l="EID";e={$_.instanceid -band 0xffff}}
@{instanceid=989045} | where-object { (& $myeid.e) -eq 6005}

Name                           Value
----                           -----
instanceid                     989045

Upvotes: 1

Related Questions