Public/Switch-DockerContainerType.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
<#
    .SYNOPSIS
        This function switches Docker-For-Windows (Docker CE) from Linux Container mode to Windows Container mode
        or visa versa.
 
    .DESCRIPTION
        See .SYNOPSIS
 
    .PARAMETER ContainerType
        This parameter is MANDATORY.
 
        This parameter takes a string with a value of either "Windows" or "Linux" representing the contianer
        mode that you would like to switch to.
 
    .EXAMPLE
        # Open an elevated PowerShell Session, import the module, and -
 
        PS C:\Users\zeroadmin> Switch-DockerContainerType -ContainerType Windows
         
#>

function Switch-DockerContainerType {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True)]
        [ValidateSet("Windows","Linux")]
        [string]$ContainerType
    )

    try {
        # Find DockerCli
        $DockerCliExePath = $(Get-ChildItem -Path "$env:ProgramFiles\Docker" -Recurse -File -Filter "*DockerCli.exe").FullName

        if (!$DockerCliExePath) {
            throw "Unable to find DockerCli.exe! Halting!"
        }
    }
    catch {
        Write-Error $_
        $global:FunctionResult = "1"
        return
    }

    $DockerInfo = Get-DockerInfo

    if ($($DockerInfo.DockerServerInfo.'OS/Arch' -match "windows" -and $ContainerType -eq "Linux") -or
    $($DockerInfo.DockerServerInfo.'OS/Arch' -match "linux" -and $ContainerType -eq "Windows")) {
        & $DockerCliExePath -SwitchDaemon

        [pscustomobject]@{
            OriginalDockerServerArch    = $DockerInfo.DockerServerInfo.'OS/Arch'
            NewDockerServerArch         = $($($(docker version) -match "OS/Arch")[1] -split ":[\s]+")[1].Trim()
        }
    }
    else {
        Write-Warning "The Docker Daemon is already set to manage $ContainerType containers! No action taken."
    }
}