Search code examples
powershellserver

Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Security.SecureString"


I have a problem with an app that I am creating: this app can configure from a remote device a server/PC through IP, Username, Password. There is a script I made in PowerShell that can add User with password in server (New-LocalUser), but when I'll execute it, it gives me this error

Cannot bind parameter 'Password'. Cannot convert the "System.Security.SecureString" value of type "System.String" to
type "System.Security.SecureString".

The password is saved in a temporary file and convert into secure string in PS script, so I don't understand why it doesn't work

Here the script

$path = (Get-Location).ToString() + "\..\..\script\PS\lib.ps1"
Import-Module -Name $path

$json = (Get-Location).ToString() + "\..\..\misc\json\user.json"
$userinfo = Get-Content $json | ConvertFrom-Json

$uj = (Get-Location).ToString() + "\..\..\misc\json\userToAdd.json"
$commands = Get-Content $uj | ConvertFrom-Json

$passtype = $commands.passwordType
$pass = $commands.password

if($commands.isEnable -eq "False"){
    $arg = '-Disabled '
}

if($commands.password -eq "")
{
    $arg = $arg + $commands.passwordType + '-NoPassword '
}else{
    $npass = $pass | ConvertTo-SecureString -AsPlainText -Force
    $arg = $arg + $commands.passwordType + '-Password '
}

if($commands.Description -eq ""){
    $desc = " "
}else{
    $desc = " -Description " + $commands.Description + " "
}

$cmd = "New-LocalUser -Name " + $commands.Name + $desc + $arg + $npass
$cmd
$ScriptBlock =  [scriptblock]::Create($cmd)
ExcuteRemoteCommand -serverAddress $userinfo.ip -ServerUsername $userinfo.user -ServerPassword $userinfo.password -code $ScriptBlock

if($commands.logon -eq "True"){
    $cmd = "net user " + ($commands.Name).ToString() + " /logonpasswordchg:yes"
    $cmd
    $ScriptBlock =  [scriptblock]::Create($cmd)
    ExcuteRemoteCommand -serverAddress $userinfo.ip -ServerUsername $userinfo.user -ServerPassword $userinfo.password -code $ScriptBlock
}else{
    $cmd = "net user " + ($commands.Name).ToString() + " /logonpasswordchg:no"
    $cmd
    $ScriptBlock =  [scriptblock]::Create($cmd)
    ExcuteRemoteCommand -serverAddress $userinfo.ip -ServerUsername $userinfo.user -ServerPassword $userinfo.password -code $ScriptBlock
}
Read-Host
Exit

Solution

  • I finally find a solution for my problem. I used the command NET, so here the che command line that I used

    NET USER $user $pass /ADD
    

    For the other parameters, I'll pass after it creates the user

    $pass is NOT a secure string!