Categories

Reading the trusted hosts list

One of the sessions I did at the recent PowerShell summit was on using the WSMAN cmdlets. In my experience, these cmdlets aren’t used much. This is for a couple of reasons I think – the syntax is a bit difficult and there are often other ways to perform the task.

This short series of posts will concentrate on using the WSMAN cmdlets to work with your trusted hosts list.  The trusetd hosts list is used in remoting, especially non-domain remoting or if you need to credssp. to determine which machines your machine trusts.

You can view the trusted hosts list by using the wsman provider:

£> ls WSMan:\localhost\Client\TrustedHosts


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

Type            Name                   SourceOfValue   Value
----            ----                   -------------   -----
System.String   TrustedHosts                           server02

if you want just the results

£> ls WSMan:\localhost\Client\TrustedHosts | select -ExpandProperty Value
server02

You can achieve the same result with Get-WSMANinstance:

Get-WSManInstance -ResourceURI winrm/config/client | select -ExpandProperty TrustedHosts

This is a bit much to type regularly so lets create a function:

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

if (Test-Connection -ComputerName $computername -Quiet -Count 1) {
  Get-WSManInstance -ResourceURI winrm/config/client -ComputerName $computername |
  select -ExpandProperty TrustedHosts
}
else {
  Write-Warning -Message "$computername is unreachable"
}

}

The function has a single parameter – the computername that defaults to the local machine.

Run Test-Connection to ensure that you can connect to the machine (-Quiet returns a boolean rather than the ping information). If you can connect use Get-WSMANinstance to fetch the trusted hosts data.

If Test-Connection doesn’t contact the remote machine use Write-Warning to output a message.

Leave a Reply