Share via

PowerShell variable changes when used remotely

sigfried 81 Reputation points
2022-07-12T12:25:24.8+00:00

Hello, I'm experiencing a weird situation where a PowerShell variable changes behaviour when used in an Invoke-Command. The variable is a System.Array type and it contains one or more active directory groups that will be added to the local admins group on remote servers. Here's the simple code:

$sessionOB = New-PSSession -ComputerName $domainComputer -Credential $domainCreds  
Invoke-Command -Session $sessionOB -ScriptBlock {  
        $args[0] | ForEach-Object {  
            Add-LocalGroupMember -Group "Administrators" -Member $_ -Confirm:$false  
        }  
  
 } -ArgumentList $ADGroups   

What happens is that only the first AD group in the $ADGroups variable gets added. If I run the same code locally (without the invoke-command of course) it works. The code is so simple that I can't see obvious mistakes... any clue?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Rich Matheisen 48,116 Reputation points
2022-07-12T14:46:49.127+00:00

You can try each of these; they all should work:

# Ugly  
$sessionOB = New-PSSession -ComputerName $domainComputer -Credential $domainCreds  
Invoke-Command -Session $sessionOB -ScriptBlock {  
    $args[0] | ForEach-Object {  
        Add-LocalGroupMember -Group "Administrators" -Member $_ -Confirm:$false  
    }    
} -ArgumentList (,$ADGroups)  
  
# Better  
$sessionOB = New-PSSession -ComputerName $domainComputer -Credential $domainCreds  
Invoke-Command -Session $sessionOB -ScriptBlock {  
    $Using:ADgroups | ForEach-Object {  
        Add-LocalGroupMember -Group "Administrators" -Member $_ -Confirm:$false  
    }  
}  
  
# Probably the best  
$sessionOB = New-PSSession -ComputerName $domainComputer -Credential $domainCreds  
Invoke-Command -Session $sessionOB -ScriptBlock {  
    Add-LocalGroupMember -Group "Administrators" -Member $Using:ADGroups -Confirm:$false  
}  

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. sigfried 81 Reputation points
    2022-07-12T12:34:41.687+00:00

    obviously this works:

    $ADGroups | ForEach-Object {  
            Invoke-Command -Session $sessionOB -ScriptBlock {  
                  
                    Add-LocalGroupMember -Group "Administrators" -Member $args[0] -Confirm:$false  
      
            } -ArgumentList $_  
        }  
    

    However, the code in the first post should work too... !

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.