无法将类型“ System.String”的“ System.Security.SecureString”值转换为类型“ System.Security.SecureString”

时间:2019-12-19 11:57:54

标签: powershell server ps1

我正在创建的应用程序有问题:该应用程序可以通过IP,用户名,密码从远程设备配置服务器/ PC。我在PowerShell中制作了一个脚本,可以在服务器(New-LocalUser)中为用户添加密码,但是当我执行该脚本时,就会出现此错误

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

密码保存在一个临时文件中,并在PS脚本中转换为安全字符串,所以我不明白为什么它不起作用

此处是脚本

$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

1 个答案:

答案 0 :(得分:0)

我终于找到了解决我问题的方法。我使用了命令NET,因此这里使用的是che命令行

NET USER $user $pass /ADD

对于其他参数,我将在创建用户之后通过

  

$ pass是不是个安全字符串!