Don't understand why it won't work

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

This topic contains 2 replies, has 3 voices, and was last updated by

Senior Moderator
4 weeks ago.

  • Author
  • #178788

    Topics: 1
    Replies: 0
    Points: 12
    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

    Topics: 1
    Replies: 1552
    Points: 2,700
    Helping Hand
    Rank: Community Hero

    Hmmm ... for me

    $tot = 0
    Get-ChildItem |
            $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: 1085
    Points: 3,651
    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 ?

You must be logged in to reply to this topic.