PowerShell: Purge User Outlook Profile

# Purge-User-Outlook-Profile.ps1

# Set folder path
$folderToDelete="$env:localappdata\Microsoft\Outlook";

function purgeFolder($path){
mkdir c:\temp -force -ea SilentlyContinue | out-null
cd c:\temp
$childItems=get-childitem $path -Recurse -force;
$filesToDelete=($childItems| ?{ !$_.PSIsContainer }).FullName;
$subFoldersToDelete=($childItems| ?{ $_.PSIsContainer }).FullName;

if (!(get-command handle.exe)){
if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))};
choco install handle -y;
$handles = handle;
}else{
$handles = handle;
}

function findPidLockedFile{
param($lockedFile)
$scrollingPid="";
$lockingPids=@();
foreach ($line in $handles) {
if ($line -like "*pid:*") {$scrollingPid=$line}
if ($line -like "*$lockedFile*") {
#[void]($scrollingPid -match "(.*)\spid:");
[void]($scrollingPid -match "pid:\s(.*)\s");
$lockingPids+=,$matches[1];}
}
$lockingPids=$lockingPids|get-unique
Write-Warning "$lockedFile is being locked by pid(s): $lockingPids"
return $lockingPids;
}

# Purge Files
foreach ($x in $filesToDelete){
try{
Remove-Item $x -Force
}
catch{
$lockingPids=findPidLockedFile $x;
$lockingPids|%{stop-process -id $_ -force};
Remove-Item $x -Force
}
}

# Then Purge Folders
if ($subFoldersToDelete){$subFoldersToDelete | Remove-Item -force -Recurse}
}

purgeFolder $folderToDelete

Leave a Reply

Your email address will not be published. Required fields are marked *