Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Invoke-Command

In my script I want to get Exchange Online distribution group members to my array $members_id.

I want to run the cmdlet Get-DistributionGroupMember on a remote server so it looks like this:

Invoke-Command -Session $Session -ScriptBlock {
    $members_id = Get-DistributionGroupMember -Identity "power_shell_test"
} -ArgumentList $members_id

After running this I get an error:

The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode.

image

When I delete $members_id = it runs good.

Please tell me if you have an idea why it works like that.

like image 229
Александр Троцко Avatar asked Dec 04 '25 13:12

Александр Троцко


1 Answers

I'm not quite sure why you're getting the error (it's probably because of how you opened $Session), but if you want the output of a remote command Get-DistributionGroupMember in a local variable $members_id you need to change your code to something like this:

$members_id = Invoke-Command -Session $Session -ScriptBlock {
    Get-DistributionGroupMember -Identity "power_shell_test"
}

Use -ArgumentList only if you want to pass the ID of the group whose members you want resolved into the scriptblock. You can either assign the parameters to variables inside the scriptblock with a Param() directive:

$members_id = Invoke-Command -Session $Session -ScriptBlock {
    Param($id)
    Get-DistributionGroupMember -Identity $id
} -ArgumentList $group_id

or use the automatic variable $args:

$members_id = Invoke-Command -Session $Session -ScriptBlock {
    Get-DistributionGroupMember -Identity $args[0]
} -ArgumentList $group_id

Alternatively you could access variables outside the scriptblock via the using: scope modifier:

$members_id = Invoke-Command -Session $Session -ScriptBlock {
    Get-DistributionGroupMember -Identity $using:group_id
}
like image 59
Ansgar Wiechers Avatar answered Dec 06 '25 05:12

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!