Welcome › Forums › General PowerShell Q&A › When to use $._ in a filter
- This topic has 3 replies, 3 voices, and was last updated 5 months ago by
Participant.
-
AuthorPosts
-
-
August 28, 2020 at 3:28 pm #253187
Fellow Powershellers,
I am trying to understand when one would and would not use $._fieldname in a filter. I have worked with two scenarios and both do the same thing
For example, lets say I am looking for when a box was rebooted.
I saw:
get-eventlog -logname system | Where-object {$_.EventID -eq ‘1074’} | ft
I then tried,
get-eventlog -logname system | Where-object EventID -eq ‘1074’ | ft
The row count appeared the same.
Can someone help explain why you would use one over the other in this scenario. Current books I have do not explain it well at least for what I just ran.
Thx
MG
-
This topic was modified 5 months ago by
Mark Gordon. Reason: wording
-
This topic was modified 5 months ago by
Mark Gordon. Reason: wording header
-
This topic was modified 5 months ago by
-
August 28, 2020 at 10:00 pm #253244
<p style=”text-align: right;”>For simple syntax you don’t need the $_, i.e. property -operator value However, if you use the scriptblock denoted by {}, you need to use $_ for the current item. If your condition syntax is complex like referencing a property of a property or doing multiple comparisons, you will need the scriptblock a nd therefore the $_.</p>
-
August 29, 2020 at 7:42 am #253286
Thx adminofthings.
-
August 29, 2020 at 11:39 am #253310
It’s actually two different sets of parameters. The docs call it ‘script block’ or ‘comparison statement’ forms. You don’t even need the quotes in the second form. The types (scriptblock or string) and the order of the arguments determine the form. You can only use $_ inside a script block.
PowerShell1234567Where-object -filterscript {$_.EventID -eq ‘1074’}Where-object -property EventID -eq -value 1074where eventid -eq 1074? eventid -eq 1074
-
-
AuthorPosts
- The topic ‘When to use $._ in a filter’ is closed to new replies.