ContainerHandling/Remove-NavContainer.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
<#
 .Synopsis
  Remove Nav container
 .Description
  Remove container, Session, Shortcuts, temp. files and entries in the hosts file,
 .Parameter containerName
  Name of the container you want to remove
 .Parameter updateHosts
  Include this switch if you want to update the hosts file and remove the container entry
 .Example
  Remove-NavContainer -containerName devServer
 .Example
  Remove-NavContainer -containerName test -updateHosts
#>

function Remove-NavContainer {
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline)]
        [string]$containerName
    )

    Process {
        if (Test-NavContainer -containerName $containerName) {
            Remove-NavContainerSession $containerName
            $containerId = Get-NavContainerId -containerName $containerName
            Write-Host "Removing container $containerName"
            docker rm $containerId -f | Out-Null
        }
        $containerFolder = Join-Path $ExtensionsFolder $containerName
        $updateHostsScript = Join-Path $containerFolder "my\updatehosts.ps1"
        $updateHosts = Test-Path -Path $updateHostsScript -PathType Leaf
        if ($updateHosts) {
            Write-Host "Removing $containerName from hosts"
            . $updateHostsScript -hostsFile "c:\windows\system32\drivers\etc\hosts" -hostname $containerName -ipAddress ""
        }

        Remove-DesktopShortcut -Name "$containerName Web Client"
        Remove-DesktopShortcut -Name "$containerName Test Tool"
        Remove-DesktopShortcut -Name "$containerName Windows Client"
        Remove-DesktopShortcut -Name "$containerName WinClient Debugger"
        Remove-DesktopShortcut -Name "$containerName CSIDE"
        Remove-DesktopShortcut -Name "$containerName Command Prompt"
        Remove-DesktopShortcut -Name "$containerName PowerShell Prompt"

        $wait = 10
        $attempts = 0
        while (Test-Path -Path $containerFolder -PathType Container) {
            Write-Host "Removing $containerFolder"
            try {
                Remove-Item -Path $containerFolder -Force -Recurse
            } catch {
                $attempts++
                if ($attempts -gt 10) {
                    throw "Could not remove $containerFolder"
                }
                Write-Host "Error removing $containerFolder (attempts: $attempts)"
                Write-Host "Please close any apps, prompts or files using this folder"
                Write-Host "Retrying in $wait seconds"
                Start-Sleep -Seconds $wait
            }
        }
    }
}
Export-ModuleMember -function Remove-NavContainer