0

I have a script to query the local Administrators group on a set of computers. I use the "-parallel" tag in Powershell 7 to improve performance. When "Invoke-Command" is run with the "-credential" flag, the script fails if -parallel is used in the foreach-object loop.

Here's the code:

#Get a list of all systems in an OU. 
$SearchBase = Get-ADOrganizationalUnit -Filter 'Name -like "*"' | Where-Object -Property DistinguishedName -Like "OU=$OU*" | Select-Object -First 1
$AllObjectsInOU = Get-ADComputer -Filter * -SearchBase $SearchBase | Select-object -Property *
$AllObjectsInOU.count
#FOr testing limit the search to the first 5 systems.
$allthings = $AllObjectsinOU[0..4]

#Get credentials with administrative access to the systems.
$credential=Get-Credential

$allthings | foreach-object -parallel{
    Invoke-Command -ComputerName $_.name -Credential $credential -ScriptBlock {Get-LocalGroupMember -Group 'Administrators'}  } 

If I leave out "-parallel", "-credential", or both, the code runs properly. However, if both flags are present, I see this error:

Invoke-Command: Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Enter your credentials.

This doesn't make sense to me. "-credential" should not require user interaction, as the credential is received beforehand.

There's an easy workaround for this: Just run Powershell with an account that has admin access to the systems. Then I can leave out the -"credential: flag. But I'm curious why the parallel flag and the credential flag conflict.

Bagheera
  • 1,358
  • 4
  • 22
  • 35
  • 1
    `-Credential $using:credential` – Santiago Squarzon Jun 15 '23 at 01:23
  • In short: To reference variable values from the caller's scope in any code that executes in a _different runspace_ (whether in a different _thread_ (`ForEach-Object -Parallel` or `Start-ThreadJob`) or a _different process_ (possibly on a remote machine) (`Start-Job`, `Invoke-Command -ComputerName ...`), you must refer to them via the [`$using:` scope](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables#using-local-variables). See the linked duplicate for details. – mklement0 Jun 15 '23 at 03:33

0 Answers0