PowerShell: Install RSAT

What problem does this solve?

dcdiag /test:dns

dcdiag : The term 'dcdiag' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ dcdiag /test:dns
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (dcdiag:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Here’s a quick function to ensure that Active Directory PowerShell module is installed on a Windows system.

function installRSAT{
    param(
        $includeAdcs=$True,
        $includeAdds=$True,
        $includeAdlds=$True,
        $includeGpmc=$True,
        $includeDhcpTools=$True,
        $includeDnsTools=$True
    )
    $ErrorActionPreference='stop'
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    #$rsatWindows7x32='https://download.microsoft.com/download/4/F/7/4F71806A-1C56-4EF2-9B4F-9870C4CFD2EE/Windows6.1-KB958830-x86-RefreshPkg.msu'
    $rsatWindows7x64='https://download.microsoft.com/download/4/F/7/4F71806A-1C56-4EF2-9B4F-9870C4CFD2EE/Windows6.1-KB958830-x64-RefreshPkg.msu'
    $rsatWindows81='https://download.microsoft.com/download/1/8/E/18EA4843-C596-4542-9236-DE46F780806E/Windows8.1-KB2693643-x64.msu'
    $rsat1709 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS_1709-x64.msu"
    $rsat1803 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS_1803-x64.msu"
    $rsatWs2016 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu"
    
    # This command does not work on Windows 2012R2
    #$releaseId=(Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseId).ReleaseId
    #Get-ItemProperty : Property ReleaseId does not exist at path HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
    #NT\CurrentVersion.
    #At line:1 char:2
    #+ (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Na ...
    #+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #    + CategoryInfo          : InvalidArgument: (ReleaseId:String) [Get-ItemProperty], PSArgumentException
    #    + FullyQualifiedErrorId : System.Management.Automation.PSArgumentException,Microsoft.PowerShell.Commands.GetItemPropertyCommand
    
    $releaseId=(Get-Item "HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion").GetValue('ReleaseID')
    $osVersion=[System.Environment]::OSVersion.Version
    [double]$osVersionMajorMinor="$($osVersion.Major).$($osVersion.Minor)"  
    $osName=(Get-WmiObject Win32_OperatingSystem).Name
    #$osType=switch ((Get-CimInstance -ClassName Win32_OperatingSystem).ProductType){
    #    1 {'client'}
    #    2 {'domaincontroller'}
    #    3 {'memberserver'}
    #    }    
    # $windowsVersion=(Get-CimInstance Win32_OperatingSystem).Version
    
    switch ($releaseId){
        1607{write-host 'Windows Server 2016 Release 1607 detected';$link=$rsatWs2016;break}
        1709{write-host 'Windows Server 2016 Release 1709 detected';$link=$rsat1709;break}
        1803{write-host 'Windows Server 2016 Release 1803 detected';$link=$rsat1803}
    }
        
    switch ($osVersionMajorMinor){
        {$_ -eq 6.0}{write-host 'Windows Server 2008 or Windows Vista detected';$link=$rsat1709;break}
        {$_ -eq 6.1}{write-host 'Windows Server 2008 R2 or Windows 7 detected';$link=$rsatWindows7x64;break}
        {$_ -eq 6.2}{write-host 'Windows Server 2012 or Windows 8.1 detected';$link=$rsatWindows81;break}
        {$_ -eq 6.3}{write-host 'Windows Server 2012 R2 detected';$link=$rsatWindows81}
    }
    
    $serverOs=$osName -match "^Microsoft Windows Server"
    $proceed=.{if($serverOs){
            Import-Module ServerManager
            $adcs=(get-WindowsFeature RSAT-ADCS).InstallState -eq 'Installed'
            $adds=(get-WindowsFeature RSAT-ADDS).InstallState -eq 'Installed'
            $adlds=(get-WindowsFeature RSAT-ADLDS).InstallState -eq 'Installed'
            $adps=(get-WindowsFeature RSAT-AD-PowerShell).InstallState -eq 'Installed'
            $gpmc=(get-WindowsFeature GPMC).InstallState -eq 'Installed'
            $dhcpTools=(get-WindowsFeature RSAT-DHCP).InstallState -eq 'Installed'
            $dnsTools=(get-WindowsFeature RSAT-DNS-Server).InstallState -eq 'Installed'       
            if(!$adps){return $True}
            elseif($includeAdcs -and !$adcs){return $True}
            elseif($includeAdds -and !$adds){return $True}
            elseif($includeAdlds -and !$adlds){return $True}
            elseif($includeGpmc -and !$gpmc){return $True}
            elseif($includeDhcpTools -and !$dhcpTools){return $True}
            elseif($includeDnsTools -and !$dnsTools){return $True}
            else{return $false}
        }else{
            return !(Get-Module -ListAvailable -Name ActiveDirectory -EA SilentlyContinue)
        }}
    if ($proceed){
        Write-host "Please wait while the program install missing modules..."
        try{
            # If OS is Windows Server, then install RSAT using a different method
            if ($serverOs) {
                # This sequence has confirmed to be valid on Windows Server 2008 R2 and above
                Write-Verbose "Importing Windows Feature: RSAT-AD-PowerShell"
                Import-Module ServerManager
                if($includeAdcs -and !$adcs){Add-WindowsFeature RSAT-ADCS}
                if($includeAdds -and !$adds){Add-WindowsFeature RSAT-ADDS}
                if($includeAdlds -and !$adlds){Add-WindowsFeature RSAT-ADLDS}
                if($includeGpmc -and !$gpmc){Install-WindowsFeature –Name GPMC}
                if($includeDhcpTools -and !$dhcpTools){Install-WindowsFeature –Name RSAT-DHCP} 
                if($includeDnsTools -and !$dnsTools){Install-WindowsFeature –Name RSAT-DNS-Server} 
                }
            else{
                Write-Verbose "This sequence targets Windows Client versions"
                $destinationFile= ($ENV:USERPROFILE) + "\Downloads\" + (split-path $link -leaf)
                Write-Host "Downloading RSAT from $link..."
                Start-BitsTransfer -Source $link -Destination $destinationFile
                $fileCheck=Get-AuthenticodeSignature $destinationFile
                if($fileCheck.status -ne "valid") {write-host "$destinationFile is not valid. Please try again...";break}
                $wusaCommand = $destinationFile + " /quiet"
                Write-host "Installing RSAT - please wait..."
                Start-Process -FilePath "C:\Windows\System32\wusa.exe" -ArgumentList $wusaCommand -Wait
                }
            return $true
            }
        catch{
            write-warning "$($error[0].Exception)"
            return $false
            }
    }else{
        Write-host "Module ActiveDirectory IS currently available on this system." -ForegroundColor Green
        return $true
        }
}
    
installRSAT

Remote Server Administration Tool (RSAT) is a feature of Windows with AD DS role installed. Other computers would exhibit errors such as this upon calling commands such as ‘dsquery’:

dsquery : The term 'dsquery' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of 
the name, or if a path was included, verify that the path is correct and try again.
At
+ dsquery * -Filter "(&(objectCategory=computer)(op ...
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (dsquery:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Below are the possible solutions to this issue. Please be advised that adding RSAT may require a server reboot. Hence, it’s a good idea to plan accordingly.

# Deprecated version

function runasAdministrator{
# Ensure that script is ran in the context of an Administrator
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "Black"
clear-host
}
else
{
# Relaunch script to run as Administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;

# Indicate that the process should be elevated
$newProcess.Verb = "runas";

# Start the new process
[System.Diagnostics.Process]::Start($newProcess);

# Exit from the current, unelevated, process
exit
}
}
runasAdministrator;

function installRSAT{
# This function currently only accounts for Windows 10 and Server OS'es. Previous versions of Windows will be ignored
$rsat1709 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS_1709-x64.msu"
$rsat1803 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS_1803-x64.msu"
$rsatWs2016 = "https://download.microsoft.com/download/1/D/8/1D8B5022-5477-4B9A-8104-6A71FF9D98AB/WindowsTH-RSAT_WS2016-x64.msu"

$osVersionNumber= (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseId).ReleaseId
$osName=(Get-WmiObject Win32_OperatingSystem).Name
switch ($osVersionNumber){
  1709 {$link=$rsat1709}
  1803 {$link=$rsat1803}
}

# If OS is Windows Server, then install RSAT using a different method
if ($osName -like "*Microsoft Windows Server*") {
    Add-WindowsFeature RSAT-AD-PowerShell
    Break;
    }

$destination= ($ENV:USERPROFILE) + "\Downloads\" + ($link.split("/")[8])

Write-Host "Downloading RSAT..." -foregroundcolor blue
Start-BitsTransfer -Source $link -Destination $destination

$fileCheck=Get-AuthenticodeSignature $destination
if($fileCheck.status -ne "valid") {write-host "Expected file doesn't exist. Please try again...";break}

$wusaCommand = $destination + " /quiet"
Write-host "Installing RSAT for Windows 10 - please wait..." -foregroundcolor blue
Start-Process -FilePath "C:\Windows\System32\wusa.exe" -ArgumentList $wusaCommand -Wait
}

installRSAT;
# Include prerequisites to run dsquery
if(!(get-command dsquery -InformationAction SilentlyContinue)){
	$dsquery=.{try{
                Add-WindowsFeature rsat -EA Stop
                return $true
                }catch{
                    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
	                $newProcess.Arguments="Get-WindowsCapability -Online |? Name -like 'Rsat.ActiveDirectory.DS-LDS.Tools*'|Add-WindowsCapability -Online;"
	                $newProcess.Verb = "runas";
	                $process=[System.Diagnostics.Process]::Start($newProcess)
                    Wait-Process -id $process.Id
                    if(get-command dsquery -InformationAction SilentlyContinue){return $true}else{return $false}
                    }
                }
	if ($dsquery){
        write-host "DSQuery is installed"
        }else{
            write-host "DSQuery is NOT installed"
            }
    }

# Import the Active Directory module for the Get-ADComputer CmdLet 
if(!(get-command get-aduser)){
    Import-Module ServerManager
    Add-WindowsFeature RSAT-AD-PowerShell
    }
Import-Module ActiveDirectory 
<# Error
PS C:\Windows\system32> Add-WindowsCapability -Name Rsat.CertificateServices.Tools~~~~0.0.1.0 -Online
Add-WindowsCapability : Add-WindowsCapability failed. Error code = 0x8024500c
At line:1 char:1
+ Add-WindowsCapability -Name Rsat.CertificateServices.Tools~~~~0.0.1.0 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-WindowsCapability], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.AddWindowsCapabilityCommand
#>

# Solution: Set Windows to Use Online updates, instead of WSUS
function installRsat{
$currentWU = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" | select -ExpandProperty UseWUServer
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value 0
Restart-Service wuauserv
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "UseWUServer" -Value $currentWU
Restart-Service wuauserv
}
installRsat

Other Notes:

# Elevate PowerShell to run as Administrator privileges
start-process powershell -verb Runas

# check if module ActiveDirectory is available
Get-Command -Module ActiveDirectory

# Search for available modules
Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property Name,State

Name State
---- -----
Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 NotPresent
Rsat.BitLocker.Recovery.Tools~~~~0.0.1.0 NotPresent
Rsat.CertificateServices.Tools~~~~0.0.1.0 NotPresent
Rsat.DHCP.Tools~~~~0.0.1.0 NotPresent
Rsat.Dns.Tools~~~~0.0.1.0 NotPresent
Rsat.FailoverCluster.Management.Tools~~~~0.0.1.0 NotPresent
Rsat.FileServices.Tools~~~~0.0.1.0 NotPresent
Rsat.GroupPolicy.Management.Tools~~~~0.0.1.0 NotPresent
Rsat.IPAM.Client.Tools~~~~0.0.1.0 NotPresent
Rsat.LLDP.Tools~~~~0.0.1.0 NotPresent
Rsat.NetworkController.Tools~~~~0.0.1.0 NotPresent
Rsat.NetworkLoadBalancing.Tools~~~~0.0.1.0 NotPresent
Rsat.RemoteAccess.Management.Tools~~~~0.0.1.0 NotPresent
Rsat.RemoteDesktop.Services.Tools~~~~0.0.1.0 NotPresent
Rsat.ServerManager.Tools~~~~0.0.1.0 NotPresent
Rsat.Shielded.VM.Tools~~~~0.0.1.0 NotPresent
Rsat.StorageMigrationService.Management.Tools~~~~0.0.1.0 NotPresent
Rsat.StorageReplica.Tools~~~~0.0.1.0 NotPresent
Rsat.SystemInsights.Management.Tools~~~~0.0.1.0 NotPresent
Rsat.VolumeActivation.Tools~~~~0.0.1.0 NotPresent
Rsat.WSUS.Tools~~~~0.0.1.0 NotPresent

# Install RSAT with one of these methods for computers that are not using WSUS
Add-WindowsCapability -Name Rsat.CertificateServices.Tools~~~~0.0.1.0 –Online
Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell

# Error
Add-WindowsCapability : Add-WindowsCapability failed. Error code = 0x800f0954
At line:1 char:1
+ Add-WindowsCapability -Name Rsat.CertificateServices.Tools~~~~0.0.1.0 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-WindowsCapability], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.AddWindowsCapabilityCommand

# Improvise
Run "gpedit.msc" > navigate to Computer Configuration\Administrative Templates\System\Specify settings for optional component installation and component repair > change it to "Enabled" > select the checkbox labeled "Download repair content and optional features directly from Windows Update instead of Windows Server Update Services (WSUS)"

Leave a Reply

Your email address will not be published. Required fields are marked *