Inside the scriptblock, variable $UserPassword
is unknown. To be able to use the variable in the scriptblock, you need to either scope it with $using:UserPassword
:
$UserPassword = ConvertTo-SecureString "test123456" -AsPlainText -Force
$pcName = "pc1", "pc2"
Invoke-Command -ComputerName $pcName -ScriptBlock {
try {
$newUser = New-LocalUser -Name "admintest" -Password $using:UserPassword -PasswordNeverExpires -ErrorAction Stop
Add-LocalGroupMember -Group "Administrators" -Member $newUser
}
catch {
Write-Warning "Could not create the new user:`r`n$($_.Exception.Message)"
}
}
OR
Have the scriptblock accept parameter(s) in a param(..)
block and call like
$UserPassword = ConvertTo-SecureString "test123456" -AsPlainText -Force
$pcName = "pc1", "pc2"
Invoke-Command -ComputerName $pcName -ScriptBlock {
param ( [securestring] $Password )
try {
$newUser = New-LocalUser -Name "admintest" -Password $Password -PasswordNeverExpires -ErrorAction Stop
Add-LocalGroupMember -Group "Administrators" -Member $newUser
}
catch {
Write-Warning "Could not create the new user:`r`n$($_.Exception.Message)"
}
} -ArgumentList $UserPassword
P.S.
- The group is called
Administrators
(plural)
- I have used a
try{..} catch{..}
so you will receive an error message when things go wrong