0

So close but so far...

I am trying to change a local administrator password on a Windows server using [ADSI] & PowerShell but I cannot find a way to pass a string variable when invoking and get the following error:

Exception calling "Invoke" with "2" argument(s): "Number of parameters specified does not match the expected number."
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
+ PSComputerName        : vmdeploytest1

This works, with the string in the statement:

$vmName = "vmdeploytest1"

Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
  $account = [ADSI]("WinNT://localhost/Administrator,user")
  $account.psbase.invoke("setpassword","Password123")
}

This doesn't:

$vmName = "vmdeploytest1"   
$password = '"Password123"'
$invoke = '"setpassword",'
$invokeStr = $invoke + $password

Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke($invokeStr)
}

This doesn't

$vmName = "vmdeploytest1"   
$password = '"Password123"'

Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}

This doesn't:

$vmName = "vmdeploytest1"   
$password = 'Password123'

Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}

All giving the same error. I need to be able to use a variable because I am going to generate a random password.

Guy Wood
  • 255
  • 4
  • 15
  • 1
    [`$using:password`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_variables). – Jeroen Mostert Mar 22 '19 at 16:08
  • 1
    Possible duplicate of [How can I pass a local variable to a script block executed on a remote machine with Invoke-Command?](https://stackoverflow.com/questions/35492437/how-can-i-pass-a-local-variable-to-a-script-block-executed-on-a-remote-machine-w) – Maximilian Burszley Mar 22 '19 at 16:11
  • Thanks Jeroen, did not know this! – Guy Wood Mar 22 '19 at 16:25

1 Answers1

0

Jeroen Mostert is Correct

When you pass variables into a ScriptBlock you need to prefix them with $using:

For example:

$vmName = "vmdeploytest1"   
$password = 'Password123'

Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$using:password)
}
SysEngineer
  • 354
  • 1
  • 7