Search code examples
powershellpowershell-remoting

Execute remote PS command properly


I'm trying to change passwords on more than 1000 hosts running windows server 2008/2012. They assigned to different domains, so I connect to them via their IP, all of them have PowerShell remoting open. Stuck at my script implementation. For now I just want to connect to single host and change the password of the user or admin whatever.

Here is the code I use

$username = "UserWhose Password I want to change"
$password = ConvertTo-SecureString "users old password" -AsPlainText    -Force 
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

$serverNameOrIp = "host ip address here"

$s = New-PSSession -ComputerName $serverNameOrIp -Authentication default -Credential $cred
#invoke the scriptblock remotely 
$sb = {
  "[ADSI]`$Admin=`"WinNT://$env:COMPUTERNAME/$env:USERNAME`""
  "`$Admin.SetPassword(`"Users new password`")"
}
Invoke-Command -Session $s -ScriptBlock $sb

Remove-PSSession $s

Now, the console output I get:

PS C:\> ./script

[ADSI]$Admin="WinNT://WIN-TA49U0TR9GT/Administrator"
$Admin.SetPassword("Users new password")

PS C:\>

"WinNT://WIN-TA49U0TR9GT/Administrator" belongs to remote host, my local computername and a username are different. I'm not getting any error or proper output here. The password isn't changing. If I try to run these commands manually on any host - it works.

Any suggestions? Maybe a working solutions?


Solution

  • You define the commands you want to run on the remote host as strings inside a scriptblock. When you invoke the scriptblock on the remote host it does what PowerShell does with all bare strings: echo them.

    Remove the outer quoting and escaping and the code should work as you expect:

    $sb = {
      [ADSI]$Admin = "WinNT://$env:COMPUTERNAME/$env:USERNAME"
      $Admin.SetPassword("Users new password")
    }
    

    The scriptblock already prevents variables from being expanded in the current context.