Skip to content

Install-WindowsFeatureRemote

Windows: Installs or enables a Windows Feature

#Requires -Version 5.1

[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
    [string]$Name,

    [string]$ComputerName = $env:COMPUTERNAME,

    [switch]$IncludeManagementTools,

    [switch]$Reboot,

    [pscredential]$Credential
)

Process {
    try {
        $scriptBlock = {
            Param($FeatureName, $Tools, $Restart)
            
            if (Get-Command -Name Install-WindowsFeature -ErrorAction SilentlyContinue) {
                $params = @{
                    'Name'                   = $FeatureName
                    'IncludeManagementTools' = $Tools
                    'Restart'                = $Restart
                    'ErrorAction'            = 'Stop'
                }
                $res = Install-WindowsFeature @params
            }
            else {
                $params = @{
                    'Online'      = $true
                    'FeatureName' = $FeatureName
                    'NoRestart'   = (-not $Restart)
                    'ErrorAction' = 'Stop'
                }
                $res = Enable-WindowsOptionalFeature @params
            }
            $res
        }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $invokeParams = @{
                'ComputerName' = $ComputerName
                'ScriptBlock'  = $scriptBlock
                'ArgumentList' = @($Name, $IncludeManagementTools, $Reboot)
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $invokeParams.Add('Credential', $Credential)
            }

            $result = Invoke-Command @invokeParams
        }
        else {
            $result = &$scriptBlock -FeatureName $Name -Tools $IncludeManagementTools -Restart $Reboot
        }

        $output = [PSCustomObject]@{
            Feature      = $Name
            Success      = $result.Success
            ExitCode     = $result.ExitCode
            RebootNeeded = $result.RestartNeeded
            ComputerName = $ComputerName
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $output
    }
    catch {
        throw
    }
}

Specifies the internal name of the feature to install/enable.

Specifies the name of the target computer. Defaults to the local computer.

Off

(Server only) If set, installs all management tools related to the feature.

Off

If set, reboots the computer if required by the installation.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.