0

Good afternoon. I would like to ask for help. I am trying to execute a script remotely. When doing this, I get a NULL password error. Please tell me how to be.

$pcName = @("pc1","pc2")    

Invoke-Command -ComputerName $pcName {$UserPassword = ConvertTo-SecureString "test123456" -AsPlainText -Force}

Invoke-Command -ComputerName $pcName -ScriptBlock { New-LocalUser -Name "admintest" -Password $UserPassword -PasswordNeverExpires }

Invoke-Command -ComputerName $pcName -ScriptBlock { Add-LocalGroupMember -Group "Administrator" -Member "admintest" }

P.S I'm just learning.

Theo
  • 57,719
  • 8
  • 24
  • 41

1 Answers1

0

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
Theo
  • 57,719
  • 8
  • 24
  • 41