Using Invoke-command with a do-while loop

Hi,

Im writing an Azure Function using PowerShell to run some commands on a remote computer. If my script block contains a single command then the invoke-command works fine, but it fails if I try and pass more commands in, im not seeing errors, it just doesn’t do anything.

$addADGroupMember = {
            do {
                $adGroup = Get-ADGroup -identity $groupName -errorAction SilentlyContinue
            } while (!($adGroup))

            Add-ADGroupMember -identity $groupName -members 'AD Group Members'
        }


       Invoke-Command -ComputerName $ComputerName -Credential $Using:Credential -ScriptBlock {$addADGroupMember} -SessionOption (New-PSSessionOption -SkipCACheck)
}

Do I have to save the contents of the $aadGroupMember block as a ps1 file and then reference it using the -filepath during the invoke-command? I wanted to try avoiding having multiple ps1 files.

Hi Deniscooper,
and Welcome to the forum. :wave:t4:

Does it work when you provide the scriptblock directly?

Invoke-Command -ComputerName $ComputerName -Credential $Credential -SessionOption (New-PSSessionOption -SkipCACheck) -ScriptBlock {
    do {
        $adGroup = Get-ADGroup -identity $groupName -errorAction SilentlyContinue
    } while ( -not ($adGroup))

    Add-ADGroupMember -identity $groupName -members 'AD Group Members'
}

… or how about providing the PSSession including the options completely like this?

$SessionOption = New-PSSessionOption -SkipCACheck 
$PSSession = New-PSSession -ComputerName $ComputerName -SessionOption $SessionOption -Credential $Credential
Invoke-Command -Session $PSSession -ScriptBlock {
    do {
        $adGroup = Get-ADGroup -Identity $groupName -ErrorAction SilentlyContinue
    } while ( -not ($adGroup))
    Add-ADGroupMember -Identity $groupName -Members 'AD Group Members'
}

I figured it out - I needed to remove the {} from the invoke-command script block section, so it just read

Invoke-Command -ComputerName $ComputerName -Credential $Using:Credential -ScriptBlock $addADGroupMember -SessionOption (New-PSSessionOption -SkipCACheck)```