header image

Remove a trusted host

Posted by: | December 30, 2019 Comments Off on Remove a trusted host |

Continuing our collection of routines to manage the trusted hosts this time we’ll look at how to remove a trusted host

function remove-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-Object -ExpandProperty TrustedHosts

if ($th) {
$ths = $th -split “, |,”, 0, “Regex”

$newth = ($ths -ne $trustedhost) -join “, ”

Set-WSManInstance -ResourceURI winrm/config/client -ComputerName $computername -ValueSet @{TrustedHosts = $newth}

}
else {
Write-Warning -Message “No trusted hosts to remove”
}

}
else {
Write-Warning -Message “$computername is unreachable”
}

}

 

The trick here is to get the current trusted hosts list and split on the commas to create an array. Create a new trusted hosts array that doesn’t contain the one you want to remove then use the join operator to recreate the string. Write that string back to the system.

 

Again this needs to be run with elevated privileges otherwise you’ll get an Access Denied error.

under: PowerShell

Comments are closed.

Categories