【问题标题】:Cannot convert 'System.Object[]' to the type 'System.String'无法将“System.Object[]”转换为“System.String”类型
【发布时间】:2019-05-30 08:40:10
【问题描述】:

我正在尝试与不在域环境中的远程服务器建立连接。 在没有脚本的情况下在 PowerShell 控制台上单独运行 Set-Item 时,由于某种原因它不能在脚本上运行。

$passwd = convertto-securestring -String <Password> -AsPlainText -Force 
$cred = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList "developer", $passwd
$server = Read-Host -Prompt 'Input your server IP'

Set-Item wsman:\localhost\client\TrustedHosts -Value $server -Force

$session = new-pssession -computername $server -credential $cred

当我运行上面的代码时,我收到了消息

Set-Item : 无法将 'System.Object[]' 转换为类型 参数所需的“System.String”。不支持指定的方法。

【问题讨论】:

    标签: string powershell


    【解决方案1】:

    当你在这里传递输入时,它应该是一个字符串值和一个单独的对象,如果有逗号什么的,那么$server就不再保留为字符串。 要进行强制转换,您可以通过类型转换将 $server 显式转换为 String 类型:

    [String]$server = Read-Host -Prompt 'Input your server IP'
    

    进一步,

    我希望您在Set-Item 中硬编码服务器名称,看看您是否收到错误。你不会得到它。

    Set-Item wsman:\localhost\client\TrustedHosts -Value 'YourServerHostname' -Force
    

    因此,在获取输入时验证您获得的输入类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多