Categories

Adding to the trusted hosts list

Its OK to be able to read the contents of the trusted hosts list but what about adding values to it?

function add-trustedhost {
[CmdletBinding()]
param (
[string]$trustedhost,
[string]$computername = $env:COMPUTERNAME
)

if (Test-Connection -ComputerName $computername -Quiet -Count 1) {
  $th = Get-WSManInstance -ResourceURI winrm/config/client -ComputerName $computername |
  select -ExpandProperty TrustedHosts

  if ($th) {
    $newth = $th + ", $trustedhost"
  }
  else {
    $newth = $trustedhost
  }

  Set-WSManInstance -ResourceURI winrm/config/client -ComputerName $computername -ValueSet @{TrustedHosts = $newth}
}
else {
  Write-Warning -Message "$computername is unreachable"
}

}

The function takes a computername paraneter and a string containing one or more machine names to add to the trusted host list.  This is a singe string so

“server02, servero3, server04”

NOT

“serevr02”, “server03”, “server04”

The current value in th trusted hosts list is retrieved and if it has  a current value the extra trusted host( s ) are added. If the trusted hosts list is empty the new list replaces it,  Set-WSManInstance is used to set the value.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>