Incrementing inside foreach and scriptblock in Powershell

381 views Asked by At

I hope someone can spot the error:

This is a small function inside a bigger script.

I want it to increment $i every time it iterate the foreach, but I can't get it to work. If I run only the line where $i++ is present, it will increment. The message is arriving to the users, so it works fine, it's just ignoring the $i++.

$i = 0

function Message {

    start-job -Name Col01 -InitializationScript{Import-Module RemoteDesktop} -ScriptBlock{$Users = Get-RDUserSession -ConnectionBroker $ActiveConnectionBroker -CollectionName "col01"

    foreach ($User in $Users) {

        Send-RDUserMessage -UnifiedSessionID $User.UnifiedSessionId -HostServer $User.HostServer -MessageTitle "Info" -MessageBody $using:message

        $i++
    }
}
1

There are 1 answers

1
Maxim Sagaydachny On

You have two variables with the same name "$i".

One of them is global and second one is local.

Here is an example which shows what is going on and how you can change global variable from inside a function (when you specify scope qualifier):

$i = 777

Write-Output "outside i: $i"

function do_something {

    $i=41
    for( $z=0 ; $z -lt 10 ; $z++ ){
      $global:i++
      $i++
      Write-Output "inside i: $i $global:i"
    }

}


do_something

Write-Output "i: $i"

Here is an output which is produced by above mentioned code

outside i: 777
inside i: 42 778
inside i: 43 779
inside i: 44 780
inside i: 45 781
inside i: 46 782
inside i: 47 783
inside i: 48 784
inside i: 49 785
inside i: 50 786
inside i: 51 787
outside i: 787

Have a look at documentation about scopes