Uninstalling Microsoft Security Essentials from Command Line

Recently, I came across a situation where I wanted to replace Microsoft Security Essentials on a couple of computers. The first question was how to uninstall Microsoft Security Essentials from command line. So, I looked for an Uninstall String in the registry:

PS Z:\> gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\* |? {$_.DisplayName -match "security" } | select DisplayName,UninstallString |ft -auto

DisplayName                              UninstallString
-----------                              ---------------
Microsoft Security Essentials            C:\Program Files\Microsoft Security Client\Setup.exe /x
Microsoft Baseline Security Analyzer 2.2 MsiExec.exe /I{08C3441C-4FAF-48D3-A551-70DD6031734F}
Microsoft Security Client                MsiExec.exe /I{42738DB0-FC3E-4672-A99B-9372F5696E30}

First one was promising. So, I started the PowerShell from an elevated command prompt to avoid UAC, and typed the following:

PS Z:\>$UninstallString='"C:\Program Files\Microsoft Security Client\Setup.exe" /x'

Followed by:

PS Z:\>Invoke-Command { param($UninstallString);&cmd /c $UninstallString } -ArgumentList $UninstallString

I did not yet pass a computer list with -computer parameter. This command did start the uninstall "wizard".  I did not want to baby-sit the installation, in other words, I wanted to run the uninstall silently, so I started looking at other parameters that would do it and found out that, "/s" is the parameter I was looking for. The command below took care of the uninstalls silently:

PS Z:\>$UninstallString='"C:\Program Files\Microsoft Security Client\Setup.exe" /x /s'
PS Z:\>Invoke-Command -computer (gc .\computers.txt) { param($UninstallString);&cmd /c $UninstallString } -ArgumentList $UninstallString

Where computers.txt contains the list of machines.
Update - 2012-08-08: PowerShell 3.0 has an updated syntax, that simplifies this code greatly. See this post: