forked from BornToBeRoot/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd-TrustedHost.ps1
85 lines (69 loc) · 2.78 KB
/
Add-TrustedHost.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
###############################################################################################################
# Language : PowerShell 4.0
# Filename : Add-TrustedHost.ps1
# Autor : BornToBeRoot (https://github.com/BornToBeRoot)
# Description : Add a trusted host (WinRM)
# Repository : https://github.com/BornToBeRoot/PowerShell
###############################################################################################################
<#
.SYNOPSIS
Add a trusted host (WinRM)
.DESCRIPTION
Add one or mulitple trusted host(s) (WinRM).
.EXAMPLE
Add-TrustedHost -TrustedHost "192.168.178.27", "TEST-DEVICE-02"
Confirm
Are you sure you want to perform this action?
Performing the operation "Add-TrustedHost" on target "WSMan:\localhost\Client\TrustedHosts".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): Y
.LINK
https://github.com/BornToBeRoot/PowerShell/blob/master/Documentation/Function/Add-TrustedHost.README.md
#>
function Add-TrustedHost
{
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")]
param(
[Parameter(
Position=0,
Mandatory=$true)]
[String[]]$TrustedHost
)
Begin{
if(-not([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
throw "Administrator rights are required to add a trusted host!"
}
}
Process{
$TrustedHost_Path = "WSMan:\localhost\Client\TrustedHosts"
[System.Collections.ArrayList]$TrustedHosts = @()
try{
[String]$TrustedHost_Value = (Get-Item -Path $TrustedHost_Path).Value
$TrustedHost_Value = (Get-Item -Path $TrustedHost_Path).Value
$TrustedHost_ValueOrg = $TrustedHost_Value
if(-not([String]::IsNullOrEmpty($TrustedHost_Value)))
{
$TrustedHosts = $TrustedHost_Value.Split(',')
}
foreach($TrustedHost2 in $TrustedHost)
{
if($TrustedHosts -contains $TrustedHost2)
{
Write-Warning -Message "Trusted host ""$TrustedHost2"" already exists in ""$TrustedHost_Path"" and will be skipped."
continue
}
[void]$TrustedHosts.Add($TrustedHost2)
$TrustedHost_Value = $TrustedHosts -join ","
}
if(($TrustedHost_Value -ne $TrustedHost_ValueOrg) -and ($PSCmdlet.ShouldProcess($TrustedHost_Path)))
{
Set-Item -Path $TrustedHost_Path -Value $TrustedHost_Value -Force
}
}
catch{
throw
}
}
End{
}
}