Remove server roles with verbose

Hi all.
I am trying to automate removing multiple server roles using powershell. The issue I have is that I give exclusion to which server roles i don’t want to remove and delete the rest. I try to have a verbose in place to see the roles currently removed with specific color, and for each role that finds an error to show it on the host but continue to the next one.
Here is what I made so far:

Write-Host "Removing all features " -foregroundcolor white
try{
Get-WindowsFeature | Where {$_.Name -notlike "*Storage*" -AND $_.Name -notlike "NET*" -AND $_.Name -notlike "*Defender*" -AND $_.Name -notlike "Powershell*" -AND $_.Name -notlike "WoW64*"} | Where Installed | Remove-WindowsFeature -Verbose
}
catch {
	    Write-Host "$($error[0])" -ForegroundColor Yellow
        continue
}
Write-Host "Successfully uninstalled reduntant server roles"  -foregroundcolor Green

Any help appreciated.
Thank you.

continue keyword makes sense only when we use iterations like for, foreach etc. Here everything starts at Get-WindowsFeature and finishes at Remove-WindowsFeature and you cannot make use of continue.

about_Continue - PowerShell | Microsoft Docs

Instead you can use the -ErrorAction parameter with Continue value, which is actually the default behavior unless explicitly changed by modifying $ErrorActionPreference built-in variable.

Using the $ErrorActionPreference variable - Professional Windows® PowerShell [Book] (oreilly.com)

You can then capture all errors using -ErrorVariable parameter.

...| Remove-WindowsFeature -Verbose -ErrorVariable RemoveError

$RemoveError
2 Likes

Thank you very much kvprasoon. Very informative and suits my needs.