Reputation: 3
I am struggling to resolve what should be a simple thing. I am looping through a list of computers $bcs for each $bc in $bcs.
I run the command below to remotely create the user account with the password you see, with out issue.
Invoke-Command -ComputerName $bc.Name -ScriptBlock {New-LocalUser -Name "User1" -Password (ConvertTo-SecureString 'Thisisapassword@' -AsPlainText -Force) -FullName "User One" -Description "User Create"}
Now I want to hide the pw in a ps file for use, so it's not easily seen. My issue is if I put the password in $pw let say and then use $pw in place of the password location in the command it fails. The BC I'm running on has no clue what $pw is.
Ok so I build a $command = variable for the whole thing and invoke $command. Still fails. I am just not seeing the obvious
ForEach($bc in $bcs)
{
$command = "New-LocalUser -Name 'User1' -Password (ConvertTo-SecureString $pw -AsPlainText -Force) -FullName 'User One' -Description 'User Create'"
Invoke-Command -ComputerName $bc.Name -ScriptBlock $command
}
Upvotes: 0
Views: 92
Reputation: 115
You have to pass the $pw
variable along with the script block you want to invoke on the remote computer. You don't need to send the whole thing as a string, you can just add -ArgumentList $pw
after the script block, then use $args[0]
inside the scriptblock itself. Like this:
Invoke-Command -ComputerName $bc.Name -ScriptBlock {New-LocalUser -Name "User1" -Password (ConvertTo-SecureString $args[0] -AsPlainText -Force) -FullName "User One" -Description "User Create"} -ArgumentList $pw
This works similarly to function calls, you just can't use named variables inside the script block, only the $args[i]
format.
Upvotes: 0