New-UrlAcl.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
Function New-UrlAcl {
    [CmdletBinding()] 
    Param( 

        [Parameter(Mandatory=$true)]
        [string]$Protocol,
        [Parameter(Mandatory=$true)]
        [string]$HostName,
        [Parameter(Mandatory=$true)]
        [int[]]$Port,
        [Parameter(Mandatory=$false)]
        [string]$Path = "/",
        [Parameter(Mandatory=$true)]
        [string]$SecurityContext
    )

    if($Protocol) { $Protocol = $Protocol.Trim() }
    if($HostName) { $HostName = $HostName.Trim() }
    if($Path) { $Path = $Path.Trim() }
    if($SecurityContext) { $SecurityContext = $SecurityContext.Trim() }

    if($UrlAcl -isnot [System.Array]){
        $UrlAcl = @($UrlAcl)
    }

    $baseCmd = "netsh http add urlacl"

    if(-not $Path.StartsWith("/")){
        $Path = "/$Path"
    }
    if(-not $Path.EndsWith("/")){
        $Path = "$Path/"
    }
    
    $url = "${Protocol}://${HostName}:$Port$Path"

    $cmd = "$baseCmd url=$url user=""$SecurityContext"""
    
    $result = Invoke-Expression $cmd

    if($result[1].Trim() -ne "URL reservation successfully added"){
        $failMessage = [string]::Join(". ", ($result | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }))

        throw "Failed to run command $cmd. $failMessage"
    }

    Write-Verbose "Successfully added: $url $SecurityContext"
}