clarification on $psitem or $_

Welcome Forums General PowerShell Q&A clarification on $psitem or $_

Viewing 1 reply thread
  • Author
    Posts
    • #269510
      Participant
      Topics: 22
      Replies: 22
      Points: 46
      Rank: Member

      I have kind of a dumb question regarding $psitem. Why is it that even when the pipeline output is a single object, I have to use a for loop to get $psitem working. for example

      Get-CimInstance Win32_OperatingSystem |% {$_.LocalDateTime-$_.LastBootUpTime}

      works, but

      Get-CimInstance Win32_OperatingSystem | {$_.LocalDateTime-$_.LastBootUpTime}

      gives an error

      “Expressions are only allowed as the first element of a pipeline.”

       

    • #269519
      Participant
      Topics: 17
      Replies: 1869
      Points: 3,631
      Helping Hand
      Rank: Community Hero

      Not a dumb question, you are learning. {} is script block when you call it like that, which you cannot pipe to. To create values based on arithmetic, you should use a calculated expression:

      While that gets you a value, normally you ware looking for minutes or days, so you would use New-TimeSpan to get the days and round the value:

      Also, $_ and $PSItem are tokens in the context of a row or line. Powershell uses PSObjects, which from a simple explanation is an array of hashtable. Now it’s more complex than that, but for a simple visual demonstration:

      Even if you processing a single item like you are getting from WMI in this case, it still looks like this:

      There is still an array to process, so you still need to process foreach item in the array. The calculated expression $_ is still referencing the context of the row. This is trying to keep the explanation as simple as possible, but hopefully this explains the structure and why you need the foreach.

      • This reply was modified 3 weeks, 6 days ago by Rob Simmers.
Viewing 1 reply thread
  • You must be logged in to reply to this topic.