【问题标题】:Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Security.SecureString"无法将“System.String”类型的“System.Security.SecureString”值转换为“System.Security.SecureString”类型
【发布时间】:2021-09-20 19:41:40
【问题描述】:

我正在创建的应用程序存在问题:此应用程序可以通过 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

【问题讨论】:

  • $SecurePassword = ConvertTo-SecureString 'MyPassword' –asplaintext –force
  • 包含导致错误的相关代码总是一个好主意。
  • 我刚做了这个,不行
  • 你的函数 ExcuteRemoteCommand 对参数 ServerPassword 有什么期望?从那里的错误消息来看,它被定义为[string],如果是这样,你应该向它发送一个纯文本密码,如果需要,在该函数内转换为[securestring]
  • 您不能将安全字符串作为 AsPlainText 传递给New-LocalUser,您需要对其进行序列化/反序列化,参见例如stackoverflow.com/q/34076478/1701026

标签: powershell server


【解决方案1】:

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

NET USER $user $pass /ADD

其他参数,创建用户后我会传

$pass 不是安全字符串!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 2014-03-14
    • 2017-11-24
    • 2012-09-07
    相关资源
    最近更新 更多