Powershell export and import installed Windows Server roles and features

You can use the Powershell snippet below to simply export all installed Windows Server Roles and features from a Windows 2019 Server. You can save the roles in a CSV files, and with the second command you are able to automatically install all the exported roles and features to another Windows Server.

This is an incredibly powerful tool to automatically install roles and features onto a new (clean) Windows Server, based on another already configured Windows Server.

1. Export all currently installed Windows Server roles to a .CSV file

Save the snippet below to a Powershell file (.ps1), then execute it. All of the currently installed Windows Server roles will then be exported to the file “D:\ServerRoles.csv”

# Check if script is run as administrator, if not, restart script.
param([switch]$Elevated)
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

Get-WindowsFeature | where{$_.Installed -eq $True} | select name | Export-Csv C:\ServerRoles.csv -NoTypeInformation -Verbose

2. Install Windows Server roles based on a previously generated ServerRoles.csv

Save the snippet below to a Powershell file (.ps1), then execute it. Note: this script expects the file “ServerRoles.csv” in the same directory where the script itself is located.

# Check if script is run as administrator, if not, restart script.
param([switch]$Elevated)
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

Import-Csv $PSScriptRoot"\ServerRoles.csv" | foreach{Add-WindowsFeature $_.name  }

Good luck!

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published.