在从远程机器上运行PowerShell命令时,我们需要将远程机器添加到主机机器的受信任主机列表中。
我正在使用以下命令将机器A添加到机器B的受信任主机列表中:
winrm set winrm/config/client ‘@{TrustedHosts="machineA"}’
如何将更多的机器(例如机器C、机器D)添加到机器B的可信主机列表中?
在从远程机器上运行PowerShell命令时,我们需要将远程机器添加到主机机器的受信任主机列表中。
我正在使用以下命令将机器A添加到机器B的受信任主机列表中:
winrm set winrm/config/client ‘@{TrustedHosts="machineA"}’
如何将更多的机器(例如机器C、机器D)添加到机器B的可信主机列表中?
我更喜欢使用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
winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'
Error: Invalid use of command
。 - Bruno Bieri建议答案是由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
我创建了一个模块,使得处理受信任主机变得更加容易,psTrustedHosts。您可以在GitHub上找到这个仓库,链接为这里。它提供了四个函数,使得处理受信任主机变得轻松: Add-TrustedHost
, Clear-TrustedHost
, Get-TrustedHost
, 和 Remove-TrustedHost
。您可以使用以下命令从PowerShell Gallery安装该模块:
Install-Module psTrustedHosts -Force
Add-TrustedHost 'machineC','machineD'
需要明确的是,此命令会将“machineC”和“machineD”添加到已有的主机中,而不是覆盖现有的主机。
Add-TrustedHost
命令也支持管道处理(Remove-TrustedHost
命令也是如此),因此您还可以执行以下操作:
'machineC','machineD' | Add-TrustedHost
和 @Altered-Ego 一样,但是使用 txt 文件:
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
}
-ErrorAction SilentlyContinue
"在旧版PS中是必需的,以避免虚假错误信息。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
winrm set winrm/config/client '@{TrustedHosts="ServerA"}'
会产生以下错误:
语法错误:输入必须是形式为 {KEY="VALUE"[;KEY="VALUE"]} 的格式
这个方法对我有用(在 Server 2016 上):
winrm set winrm/config/client @{TrustedHosts="ServerA"}