When to use $._ in a filter

Welcome Forums General PowerShell Q&A When to use $._ in a filter

  • This topic has 3 replies, 3 voices, and was last updated 4 weeks ago by
    js
    Participant
    .
Viewing 3 reply threads
  • Author
    Posts
    • #253187
      Participant
      Topics: 6
      Replies: 5
      Points: 28
      Rank: Member

      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 4 weeks, 1 day ago by Mark Gordon. Reason: wording
      • This topic was modified 4 weeks, 1 day ago by Mark Gordon. Reason: wording header
    • #253244
      Participant
      Topics: 0
      Replies: 81
      Points: 362
      Helping Hand
      Rank: Contributor

      <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>

    • #253286
      Participant
      Topics: 6
      Replies: 5
      Points: 28
      Rank: Member

      Thx adminofthings.

    • #253310
      js
      Participant
      Topics: 32
      Replies: 842
      Points: 2,690
      Helping Hand
      Rank: Community Hero

      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.

      • This reply was modified 4 weeks ago by js.
      • This reply was modified 4 weeks ago by js.
      • This reply was modified 4 weeks ago by js.
      • This reply was modified 4 weeks ago by js.
      • This reply was modified 4 weeks ago by js.
Viewing 3 reply threads
  • You must be logged in to reply to this topic.