Public/Enable-SpecWindowsOptionalFeature.ps1
Function Enable-SpecWindowsOptionalFeature { <# .SYNOPSIS This function adds a specified Windows optional feature. .DESCRIPTION The Enable-SpecWindowsOptionalFeature function is used to query, enable, and install a specified Windows optional feature on the system. It checks the current status of the feature and performs the necessary actions to enable it if it's not already enabled. .PARAMETER FeatureName Specifies the name of the Windows optional feature to be added. .EXAMPLE Enable-SpecWindowsOptionalFeature -FeatureName "NetFx3" This example adds the .NET Framework 3.5 feature to the system if it's not already enabled. .OUTPUTS System.Int32 This function produces the following exit codes to indicate the status of the operation: - 400: The feature was successfully enabled and installed. - 401: An error occurred while attempting to retrieve the Windows feature. - 402: The specified feature does not exist. - 403: An error occurred while enabling the feature. - 404: The feature is already installed and enabled. .NOTES Author : owen.heaume Version: 1.0 - Initial code #> [cmdletbinding()] param ( [parameter (Mandatory = $true)] [string]$FeatureName ) try { write-verbose "Querying Windows Optional Feature '$($FeatureName)'..." $FeatureStatus = Get-WindowsOptionalFeature -Online -FeatureName $FeatureName -ea Stop -ev x write-verbose "OK" } catch { write-error "Error occured trying to query the windows feature: '$($featureName)'" return 401 } If ($NULL -eq $FeatureStatus) { Write-warning "Feature '$($FeatureName)' does not exist" return 402 } switch ($featurestatus.state) { 'Disabled' { Write-Verbose "Enabling Windows Feature '$($FeatureName)'..." try { Enable-WindowsOptionalFeature -Online -FeatureName $FeatureName -NoRestart -All -ea stop -ev x Write-Verbose "OK" return 400 } catch { Write-Error "An error occurred enabling '$($FeatureName)' The error was: $x" return 403 } } 'Enabled' { Write-Warning "The feature '$($FeatureName)' is already installed" return 404 } } } |