Remove Teams Chat

Get rid of Teams Chat (Personal) Script

This post will be short, mostly sharing the script I use to remove Teams for home and small business a.k.a Teams Personal (Chat)

The script is packaged as a win32 application and installed during Autopilot deployment.

If you do not want to use a script then check out this post to remove Teams Chat without any scripts

What does the script do?

The script consists of 5 functions.

CleanUpAndExit: This function is used for Intune detection and writes a registry value to specified location, this is then used to check if the scipt/application was successfully executed.
The CleanUpAndExit function I borrowed from Peter Klapwijk: https://www.inthecloud247.com/
I tend to re-use this function a lot.

Remove-ChatIconInstantly: This function loops thru all users and sets the registry value “TaskbarMn” to 0. This makes sure that the Chat icon in the taskbar is removed at first startup.

Remove-TeamsChatIcon: This function disables the Chat icon, however using this does not automatically remove the Chat icon at first startup, requires a reboot that is why I included the Remove-ChatIconInstantly function. The registry values set are according to

Microsoft Documentation

Uninstall-TeamsChat: This function uninstalls the application using Remove-AppXPackage, it will be check if it’s present on the system and remove it for all users.

Microsoft Documentation

Prevent-Reinstall: This function makes sure that Teams Chat will not be re-installed on the system again, I have seen it being re-installed after Microsoft Updates etc. With this function you will no longer need a ProActive Remediation to find and uninstall the application again. It sets the following registry file ConfigureChatAutoInstall. The function temporary creates a scheduled task to be able to set the registry value as TrustedInstaller. This function was originally created by GrooveMaster17

Microsoft Documentation

Remove-TeamsChat Script

<#
	.SYNOPSIS
		Removes Teams for Home and small business (Teams Chat)
	
	.DESCRIPTION
		CleanUpAndExit: Used for Intune detection, if successfully installed or not
		Remove-ChatIconInstantly: Removes the Teams Chat icon for all user profiles (No reboot required)
		Remove-TeamsChatIcon: Disables Teams Chat icon on the taskbar
		Uninstall-TeamsChat: Uninstalls Teams Chat application
		Prevent-Reinstall: Prevents Teams Chat from being reinstalled from Windows Updates
		Log is written to Windows\temp folder

	.NOTES
		NAME: 		Remove-TeamsChat.ps1
		AUTHOR: 	Everything365.online
		LASTEDIT: 	2023-03-23
		
	.PARAMETER $StoreResults
		Set this parameter to fit your needs, location for Intune detection registry
		
	.PARAMETER $Key
		Set this parameter to fit your needs, location for Intune detection registry
	
	.LINK
		Original prevent reinstall script: https://github.com/groovemaster17/IntunePowershell/blob/main/removeChat.ps1
	
	.LINK
		CleanUpAndExit function from Peter Klapwijk: https://www.inthecloud247.com/
	
	.LINK
		Everyting365.online webpage: https://www.everthing365.online

#>

#----------------------------------------------------------[Start Logging]----------------------------------------------------------

#Log File Info
$NOW = Get-Date -Format "yyyyMMdd-hhmmss"
$LogPath = "$ENV:WINDIR\Temp\TeamsChatRemoval-$NOW.log"

Start-Transcript -path $LogPath

#-----------------------------------------------------------------------------------------------------------------------------------

If ($ENV:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
    Try {
        &"$ENV:WINDIR\SysNative\WindowsPowershell\v1.0\PowerShell.exe" -File $PSCOMMANDPATH
    }
    Catch {
        Throw "Failed to start $PSCOMMANDPATH"
    }
    Exit
}

#-----------------------------------------------------------[Functions]-------------------------------------------------------------

Function CleanUpAndExit() {
    Param(
        [Parameter()][int]$ErrorLevel = 0
    )
	
    # Write results to registry for Intune Detection
	$StoreResults = "\Contoso\RemoveTeamsChat"
    $Key = "HKEY_LOCAL_MACHINE\Software$StoreResults"
    $NOW = Get-Date -Format "yyyyMMdd-hhmmss"

    If ($ErrorLevel -eq 0) {
        [Microsoft.Win32.Registry]::SetValue($Key, "Success", $NOW)
    } else {
        [Microsoft.Win32.Registry]::SetValue($Key, "Failure", $NOW)
        [Microsoft.Win32.Registry]::SetValue($Key, "Error Code", $Errorlevel)
    }
    
    # Exit Script with the specified ErrorLevel
    EXIT $ErrorLevel
}

#-----------------------------------------------------------------------------------------------------------------------------------

function Remove-ChatIconInstantly {
    $Success = $false
    
    foreach ($userPath in (Get-ChildItem "Registry::HKEY_USERS\" | Where-Object { $_.Name -notmatch '_Classes|S-1-5-18|S-1-5-19|S-1-5-20' })) {
        $username = $userPath.PSChildName

        try {
            $taskbarMnPath = "HKEY_USERS\$username\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"

            # Set the registry values
            [Microsoft.Win32.Registry]::SetValue($taskbarMnPath, 'TaskbarMn', 0, 'DWORD')
        }
        catch {
            Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
            $Success = $false
            return $Success
        }
    }

    $Success = $true
    Write-Host "Registry values are set correctly for all users."
    return $Success
}

#-----------------------------------------------------------------------------------------------------------------------------------

function Remove-TeamsChatIcon {
	$Success = $false
	
    try {
        $registryPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Windows Chat"
        if (!(Test-Path $registryPath)) {
            New-Item $registryPath
        }
        Set-ItemProperty $registryPath "ChatIcon" -Value 3
        Write-Host "Removed Teams Chat icon from taskbar"
		$Success = $true
    } 
	catch {
        Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
		$Success = $false
    }
	
	return $Success
}

#-----------------------------------------------------------------------------------------------------------------------------------

Function Uninstall-TeamsChat {
    $Success = $false

    # Check if Teams Chat is installed
    $TeamsPackage = Get-AppxPackage MicrosoftTeams* -ErrorAction SilentlyContinue
    if (!$TeamsPackage) {
        Write-Host "Teams Chat is not installed."
        return $true
    }

    Try {
        # Uninstall Teams Chat
        $TeamsPackage | Remove-AppxPackage -AllUsers -ErrorAction Stop
        Get-AppxProvisionedPackage -Online | Where-Object {$_.PackageName -like "*MicrosoftTeams*"} | Remove-AppxProvisionedPackage -Online -Verbose -ErrorAction Stop
        Write-Host "Successfully uninstalled Teams Chat."
        $Success = $true
    }
    Catch {
        Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
        $Success = $false
    }

    return $Success
}

#-----------------------------------------------------------------------------------------------------------------------------------

Function Prevent-Reinstall {
	$Success = $false
	
    Try {
        # Set up scheduled task to be able to write to registry as TrustedInstaller
        $Action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-executionpolicy bypass -command "reg.exe add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Communications /v ConfigureChatAutoInstall /t REG_DWORD /d 0 /f | Out-Host"'
        $Principal = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators"
        Register-ScheduledTask -TaskName 'uninstallChat' -Action $Action -Principal $Principal
        $svc = New-Object -ComObject 'Schedule.Service'
        $svc.Connect()
        $user = 'NT SERVICE\TrustedInstaller'
        $folder = $svc.GetFolder('\')
        $task = $folder.GetTask('uninstallChat')

        # Start Task
        $task.RunEx($null, 0, 0, $user)
        Start-Sleep -Seconds 5

        # Kill Task
        $task.Stop(0)

        # Remove task From Task Scheduler
        Unregister-ScheduledTask -TaskName 'uninstallChat' -Confirm:$false
		Write-Host "Successfully created registry to prevent reinstallation"
		
		$Success = $true
    }
    Catch {
        Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
		$Success = $false
		
    }
	
	return $Success
}

#--------------------------------------------------[Start Removal of Teams Chat]---------------------------------------------------

$RemoveChatIconInstantly = Remove-ChatIconInstantly
$RemoveTeamsChatIcon = Remove-TeamsChatIcon
$UninstallTeamsChat = Uninstall-TeamsChat
$PreventReinstall = Prevent-Reinstall

# If all functions ran successfully, exit with error code 0
if ($RemoveChatIconInstantly -and $RemoveTeamsChatIcon -and $UninstallTeamsChat -and $PreventReinstall) {
    CleanUpAndExit -ErrorLevel 0
} else {
    CleanUpAndExit -ErrorLevel 101
}

#----------------------------------------------------------[Stop Logging]----------------------------------------------------------

Stop-Transcript

Deploying the script during pre-provisioning

If you are running Autopilot pre-provisioning you need to remove or edit the log output part, this will fail during pre-provisioning due to using transcript. You can still have a log output to a file instead.

Changed log method

#--[Start Logging]--
# Log File Info
$Now = Get-Date -Format "yyyyMMdd-HHmmss"
$LogPath = "$ENV:WINDIR\Temp\TeamsChatRemoval_$Now.log"

# Write to log file
Write-Output "Removed Teams Chat icon from taskbar" | Out-File -FilePath $LogPath -Append

#--[Stop Logging]--
Write-Output "Logging finished. Script execution completed." | Out-File -FilePath $LogPath -Append
$LogPath = $null

How to deploy the script during Autopilot deployment

We will package the script as a Win32 application using the Win32 Content Prep Tool

Details on how to use the content prep tool can be found here

Once you have package the Remove-TeamsChat.ps1 file as a Win32 application we will upload it to Intune as a new app.

Intune Install Command

Install command: powershell -executionpolicy bypass -file Remove-TeamsChat.ps1

Remove Teams Chat. Intune install command for PowerShell script
Install command

Detection rule

Make sure you modify this to fit the changes you made in the script for the CleanUpAndExit function. This is the only variables you need to modify in the script.

Intune Detection Rule
Detection rule

Assignments

Assign it according to your requirements, in this case we use all users and required install.
To make sure this is installed during the deployment process you should also modify your Enrollment Status Page and set it as a required app.

Block device use until required apps are installed if they are assigned to the user/device.

That’s it, Teams Chat is permanently gone and will never come back.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
yorick
yorick
2 months ago

Wouldn’t a remediation script be more ideal in Intune?