93

要从远程机器上运行 powershell 命令,我们必须将远程机器添加到主机的受信任主机列表中。

我正在使用以下命令将机器 A 添加到机器 B 的受信任主机:

winrm set winrm/config/client ‘@{TrustedHosts="machineA"}’

如何将更多机器说机器C,机器D添加到机器B的受信任主机列表中?

4

5 回答 5

144

我更喜欢使用 PSDrive WSMan:\

获取 TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

设置 TrustedHosts

提供一个以逗号分隔的计算机名称字符串

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

或(危险的)通配符

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

要附加到列表,-Concatenate可以使用参数

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
于 2015-07-13T08:06:00.520 回答
71
winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'
于 2014-10-21T22:14:20.493 回答
13

Loïc MICHEL建议的答案盲目地将新值写入 TrustedHosts 条目。
我相信,更好的方法是首先查询 TrustedHosts。
正如Jeffery Hicks 在 2010 年发布的那样,首先查询 TrustedHosts 条目:

PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current
于 2016-07-23T14:16:57.087 回答
7

我创建了一个模块psTrustedHosts来稍微轻松地处理受信任的主机。可以在 GitHub 上找到 repo 。它提供了四种功能,使与受信任主机的工作变得容易:Add-TrustedHostClear-TrustedHostGet-TrustedHostRemove-TrustedHost。您可以使用以下命令从 PowerShell 库安装模块:

Install-Module psTrustedHosts -Force

在您的示例中,如果您想附加主机“machineC”和“machineD”,您只需使用以下命令:

Add-TrustedHost 'machineC','machineD'

需要明确的是,这会将主机“machineC”和“machineD”添加到任何已经存在的主机,它不会覆盖现有主机。

Add-TrustedHost命令也支持管道处理(Remove-TrustedHost命令也是如此),因此您还可以执行以下操作:

'machineC','machineD' | Add-TrustedHost
于 2017-11-28T05:23:35.013 回答
0

与@Altered-Ego 相同,但使用 txt.file:

Get-Content "C:\ServerList.txt"
machineA,machineB,machineC,machineD


$ServerList = Get-Content "C:\ServerList.txt"
    $currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
    if ( ($currentTrustHost).Length -gt "0" ) {
        $currentTrustHost+= ,$ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
        }
    else {
        $currentTrustHost+= $ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
    }

在旧 PS 版本中需要" -ErrorAction SilentlyContinue" 以避免虚假错误消息:

PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   machineA,machineB,machineC,machineD
于 2021-02-04T13:33:32.337 回答