无法将“System.Object[]”转换为“System.String”类型

Dor*_*may 4 string powershell

我正在尝试与不在域环境中的远程服务器建立连接。在没有脚本的情况下在 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
Run Code Online (Sandbox Code Playgroud)

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

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

Ran*_*tta 6

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

[String]$server = Read-Host -Prompt 'Input your server IP'
Run Code Online (Sandbox Code Playgroud)

更远,

我希望您在 中对服务器名称进行硬编码Set-Item,看看您是否收到错误消息。大多数情况下你不会得到它。

Set-Item wsman:\localhost\client\TrustedHosts -Value 'YourServerHostname' -Force
Run Code Online (Sandbox Code Playgroud)

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