function Remove-Office { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter()] $TARGETDIR = 'd:\logs' ) begin{ function Write-Log { Param ( [Parameter(Mandatory=$true)] [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 } } $global:uninstallLog = Join-Path $TARGETDIR uninst.log New-Item $TARGETDIR -ItemType Directory -Force } Process { Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object { $_.DisplayName -match 'Office' } | 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 ($pscmdlet.ShouldProcess($productCode)) { Write-Log "Uninstall command detected as $($_.UninstallString) Attempting silent uninstall" Start-Process msiexec.exe -ArgumentList $arglist -Wait -NoNewWindow -ErrorAction Stop } else { Write-Host '"WhatIf" has been selected no call to Start-Process' -FOre Yellow } } else { Write-Log 'Product code not found' -Color Red } } } Catch { Write-Log "Error: $($_.Exception.Message)" -Color Red } } } } Remove-Office -Verbose -WhatIf