Don't understand why it won't work

Welcome Forums General PowerShell Q&A Don't understand why it won't work

Viewing 2 reply threads
  • Author
    Posts
    • #178788
      Participant
      Topics: 3
      Replies: 4
      Points: 65
      Rank: Member

      Simple but don't understand

      If I type

      $tot =0

      gci |%{$tot += $_.length}

      It will return value

      $tot = gci |%{$tot += %_.length}

      It return nothing.

      why ?

    • #178806
      Participant
      Topics: 2
      Replies: 1688
      Points: 3,345
      Helping Hand
      Rank: Community Hero

      Hmmm ... for me

      $tot = 0
      Get-ChildItem |
          ForEach-Object{
              $tot += $_.length
          }

      ... does not return anything ... if you meant it fills the variable $tot with the cumulated sizes of the files of the current directory – yes it does that.

      But what should "%_" be? What do you expect it to do? Don't you get an error (a lot of errors?)

    • #178932
      Senior Moderator
      Topics: 8
      Replies: 1152
      Points: 4,000
      Helping Hand
      Rank: Community Hero

      $tot = gci |%{$tot += %_.length}

      REgardless of the syntax , it won't return anything. The scriptblock should spit something for the $tot variable to catch. In this case its always caught in $tot inside the foreach statement.

      As @Olaf-Soyk mentioned, didn't you get any errors with that syntax ?

Viewing 2 reply threads
  • The topic ‘Don't understand why it won't work’ is closed to new replies.