Output with Invoke-Command

Hello,

Powershell noob here. Have a question regarding the output when you invoke a scriptblock with Invoke-Command.

I am trying to do bulk password resets with names stored in an array and passing that array through a foreach loop to Set-ADAccountPassword. If I run this command, my write-host outputs that only the first name in the array had the password changed. But if I run this same code directly from the DC, it correctly says that all the users passwords have been changed.

Is this simply an output issue with Write-Host when using Invoke-Command? Or is really only 1 of the users named being passed across to the other machine?

Thanks!

$UserN = @("one","two","three","four")
$Cred = ....

Invoke-Command -ComputerName XXX.XX.XX.XX -Credential $Cred -ArgumentList $UserN `
-ScriptBlock{
     param($UserN) 
foreach ($user in $UserN){
Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "XXXXXX" -Force)
Write-Host "`nPassword changed for $user!" -ForegroundColor Yellow 
}
}

It looks like you are running / invoke that on a remote machine?

Do you have PowerShell v3 or newer?

$UserN = "one", "two", "three", "four"
$Cred  = 'P@ssw0rd'

Invoke-Command -ComputerName XXX.XX.XX.XX -Credential $Cred -ScriptBlock {
    foreach ($user in $using:UserN) {
        Set-ADAccountPassword -Identity $user -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "XXXXXX" -Force) -verbose
    }
}

Set-ADAccountPassword can accept pipeline input. So in addition to not needing to use Invoke-Command, you can get rid of the foreach loop as well.
Something like
[pre]
$userN | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “XXXXXX” -Force)
[/pre]
should work.

You could use implicit remoting, below article explains the beauty of it.

https://blogs.technet.microsoft.com/heyscriptingguy/2013/09/08/remoting-the-implicit-way/

@AlexW : Yes, I should have clarified. I am using Invoke-Command to invoke on a remote machine which is also on another domain. Yes latest PS versions are installed.

@Wes : Don’t I still need to use Invoke-Command in order to execute the command on the remote machine?

Should have also clarified better: I am not using Invoke-Command when running the code from the remote machine. I am just using the basic foreach loop through the array, which works fine. It’s only when I use Invoke from my machine to the target machine that the Output says only the first user in the array had the password changed.