WinRmTrustedHost.psm1
function Get-WinRMTrustedHost { <# .SYNOPSIS Fetches the current Trusted Hosts List #> return [String[]]((get-item WSMAN:\localhost\Client\TrustedHosts).value -split ',') } function Test-WinRMTrustedHost ([String]$Name,[Switch]$Force) { <# .SYNOPSIS Tests if the specified trusted host entry is already part of the trusted hosts list #> [String[]]$existingWinRMTrustedHosts = Get-WinRMTrustedHost if ($existingWinRMTrustedHosts -eq '*' -and -not $Force) { write-verbose "Trusted Hosts is currently set to all hosts ('*') but a named host $Name was specified. Please specify -Force to OVERWRITE the all hosts wildcard if that is your intention" return $true } if ($Name -in $existingWinRMTrustedHosts) { return $true } #If we got this far, fail the test by default return $false } function Set-WinRMTrustedHost ([String[]]$Name) { <# .SYNOPSIS Overwrites whatever the existing Trusted Host Setting is with a new value #> set-item WSMAN:\localhost\Client\TrustedHosts -Value ($Name -join ',') } function Add-WinRMTrustedHost ([String]$Name, [Switch]$Force) { <# .SYNOPSIS Adds a host to the existing Trusted hosts setting, respecting if a wildcard has been set. #> if (Test-WinRMTrustedHost $Name) { write-verbose "$Name already exists in Trusted Hosts list. Skipping..." return } [String[]]$existingWinRMTrustedHosts = Get-WinRMTrustedHost if ($existingWinRMTrustedHosts -eq '*' -and -not $Force) { write-warning "Trusted Hosts is already set to all hosts ('*'). Skipping the add of $Name unless you specify -Force which will OVERWRITE the all hosts wildcard" return } #If a wildcard was specified, it must override everything else. Otherwise, append if ($Name -eq '*' -or $Force) { Set-WinRMTrustedHost $Name return } #Process normal append if none of the specialty cases above apply Set-WinRMTrustedHost ($existingWinRMTrustedHosts + $Name) } [DscResource()] class WinRMTrustedHost { #Trusted Host to add. You can comma separate this. [DscProperty(Key)] [string]$Name #Overwrite any existing settings. This can clear a wildcard if already specified [Switch]$Force # Tests if the resource is in the desired state. [bool] Test() { return (Test-WinRMTrustedHost -Name $this.name -Force:$this.force) } # Sets the desired state of the resource. [void] Set() { if ($this.Test()) {throw "Set was requested but Test passed. This should not happen."} Add-WinRMTrustedHost -Name $this.Name -Force:$this.force } # Gets the resource's current state. [WinRMTrustedHost] Get() { $this.name = Get-WinRMTrustedHost -join ',' return $this } } |