$AppDisplayName = 'Office' $TARGETDIR = 'd:\logs' $global:uninstallLog = Join-Path $TARGETDIR uninst.log function Write-Log { Param ( [Parameter(Mandatory)] [String]$Message, $Color = 'Green', [string]$logfile = $global:uninstallLog ) Process { $msg = '[{0:dd\MM\yyy HH:mm}{1}' -f [datetime]::Now, $Message if($logfile){$msg | Out-File $logfile -Encoding ascii} $msg | Write-Host -ForegroundColor $Color } } function Get-UninstallInfo { Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -match $AppDisplayName} } $WhatIfPreference = $true $global:ShouldProcess = $false $savedVerbosePreference = $VerbosePreference $VerbosePreference = 'Continue' New-Item $TARGETDIR -ItemType Directory -Force Get-UninstallInfo | ForEach-Object{ Write-Verbose "Processing $($_.DisplayName)" Try { if ($_.DisplayName -match '365') { Write-Log "$($ENV:COMPUTERNAME) is already using O365 , no need to uninstall" } else { if($_.UninstallString -match '{(.*)}'){ $productCode = $matches[1] Write-Log "Non Office 365 Detected - $productcode - Querying Uninstall command" $arglist = '/x', $productCode, '/qn', '/norestart', '/L*v', $uninstallLog Write-Verbose "ProductCode is set to $productCode" if($ShouldProcess){ Write-Log "Uninstall command detected as $($_.UninstallString) Attempting silent uninstall" Start-Process msiexec.exe -ArgumentList $arglist -Wait -NoNewWindow -ErrorAction Stop } else { Write-Verbose '"$ShouldProcess" is set to "$false"' } } else { Write-Log 'Product code not found' -Color Red } } } Catch { Write-Log "Error: $($_.Exception.Message)" -Color Red } } $VerbosePreference = $savedVerbosePreference $WhatIfPreference = $false