======Microsoft - Scripting - PowerShell - Snippets - WinRM TrustedHosts====== A snippet to store the current WinRM TrustedHosts in a avariable and set it to * at the start of a script, so that a New-PSSession command does not error on hosts not part of the same domain as the computer running the script, and restore the old TrustedHosts value at the end of the script. See [[microsoft:scripting:powershell:snippets:logging]] for the Log-* funtions. =====Set TrustedHosts to * at the start====== # Store the current WinRM TrustedHosts of the local machine to restore at the end of this script, # and set the WinRM TrustedHosts to *. try { Log-Info "Enabling WinRM on the local system if necessary." # Enable WinRM if not already enabled to prevent Set-Item from asking if it's OK to start the WinRM service. #. "$env:systemroot\system32\winrm.cmd" quickconfig -force # Windows 7 does not support -force, only -quiet. . "$env:systemroot\system32\winrm.cmd" quickconfig -quiet Log-Info "Getting the current TrustedHosts list." # Store the current TrustedHosts value. $strOldTrustedHosts = (Get-Item wsman:\localhost\Client\TrustedHosts -ErrorAction Stop).Value Log-Info "Old TrustedHosts: $strOldTrustedHosts." Log-Info "Overwriting TrustedHosts with value: *" # Set WinRM TrustedHosts to * on the local machine. Set-Item wsman:\localhost\Client\TrustedHosts -Value "*" -ErrorAction Stop -Force } catch { Log-Error "Could not add * to the TrustedHosts. Quitting." Log-Error $Error[0] Exit } =====Restore previous TrustedHosts value at the end===== # Restore the old WinRM TrustedHosts of the local machine. if ($strOldTrustedHosts -ne "") { try { Log-Info "Restoring the old TrustedHosts list." Log-Info "Overwriting TrustedHosts with value: $strOldTrustedHosts" Set-Item wsman:\localhost\Client\TrustedHosts -Value "$strOldTrustedHosts" -ErrorAction Stop -Force } catch { Log-Error "Could not set the TrustedHosts to: $strOldTrustedHosts. Quitting." Log-Error $Error[0] Exit } }