I build myself the following code in order to uninstall MS Teams (personal) from the computer.
My goal is to uninstall it from every user profile on the PC and in the best case if a new user logs in, it should not be installed or appear for that user.
# Check, if "MS Teams (personal)" is installed, stop (if necessary) and then proceed
if (Get-AppxPackage -Name MicrosoftTeams)
{
Get-Process -Name "msteams"
Stop-Process -Name "msteams" -Force
Start-Sleep 5
$uninstall_Teams_Free
}
# Uninstall Teams
$uninstall_Teams_Free = {
Get-AppxPackage -Name MicrosoftTeams -AllUsers | Remove-AppxPackage -AllUsers
Start-Sleep -Seconds 5
}
Just to make sure nothing gets messed up too fast I've put a sleep for 5 seconds.
Would this be the correct attempt? Any tips or tricks are welcome.
$uninstall_Teams_Free
is just a script block in your code, it doesn't do anything unless you invoke it, for example with &
:
# define
$sb = { 1 + 1 }
# invoke
& $sb # 2
You should also consider that, because PowerShell code is parsed and executed line-by-line, the script block has to be defined before the if
condition, otherwise it won't exist!
Try with this approach, you don't really need a script block at all in your code:
# Check, if "MS Teams (personal)" is installed
if ($pkg = Get-AppxPackage -Name MicrosoftTeams -AllUsers) {
# If the process is running
Get-Process -Name 'msteams' -ErrorAction SilentlyContinue |
# Try to stop it and stop the script if fails to stop
Stop-Process -Force -ErrorAction Stop
Start-Sleep 5
# Remove the existing app packages
$pkg | Remove-AppxPackage -AllUsers
}