Private/InstallFeatureDism.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
function InstallFeatureDism {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True)]
        [string]$Feature,   # Microsoft-Hyper-V, Containers, etc

        [Parameter(Mandatory=$False)]
        [switch]$AllowRestarts,

        [Parameter(Mandatory=$False)]
        [string]$ParentFunction
    )

    # Check to see if the feature is already installed
    $FeatureCheck = Get-WindowsOptionalFeature -FeatureName $Feature -Online
    if ($FeatureCheck.State -ne "Enabled") {
        if ($ParentFunction) {
            Write-Warning "Please re-run $ParentFunction function AFTER this machine (i.e. $env:ComputerName) has restarted."
        }

        try {
            # Don't allow restart unless -AllowRestarts is explictly provided to this function
            Write-Host "Installing the Feature $Feature..."
            $FeatureInstallResult = Enable-WindowsOptionalFeature -Online -FeatureName $Feature -All -NoRestart -WarningAction SilentlyContinue
            # NOTE: $FeatureInstallResult contains properties [string]Path, [bool]Online, [string]WinPath,
            # [string]SysDrivePath, [bool]RestartNeeded, [string]$LogPath, [string]ScratchDirectory,
            # [string]LogLevel
        }
        catch {
            Write-Error $_
            $global:FunctionResult = "1"
            return
        }
    }
    else {
        Write-Warning "The Feature $Feature is already installed! No action taken."
    }

    if ($FeatureInstallResult.RestartNeeded) {
        if ($AllowRestarts) {
            Restart-Computer -Confirm:$false -Force
        }
        else {
            Write-Warning "You must restart in order to complete the Feature $Feature installation!"
        }
    }

    $FeatureInstallResult
}