Skip to content

Instantly share code, notes, and snippets.

@theunrepentantgeek
Created May 29, 2020 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theunrepentantgeek/0ba1c7611065a6149466b28f3dbdef65 to your computer and use it in GitHub Desktop.
Save theunrepentantgeek/0ba1c7611065a6149466b28f3dbdef65 to your computer and use it in GitHub Desktop.
PowerShell scripts to archive old messages from Inbox
. ./script-library.ps1
[console]::OutputEncoding = New-Object System.Text.UTF8Encoding
$mailboxName = "<mailboxname>"
$outlook = new-object -com outlook.application;
Write-ColorText -Green "[✓] Connected to Outlook"
$ns = $outlook.GetNameSpace("MAPI");
$mailbox = $ns.Folders.Item($mailboxName)
$inbox = $mailbox.Folders.Item("Inbox")
Write-ColorText -Green "[✓] Found Inbox"
$archiveFolder = $mailbox.Folders.Item("Archive")
Write-ColorText -Green "[✓] Found Archive Folder"
$yearFolder = $null
$monthFolder = $null
$messages = $inbox.Items
$messageCount = $messages.Count
Write-ColorText -Gray "[○] Scanning $messageCount messages"
$threshold = (get-date).AddDays(-90).Date
Write-ColorText -White "[○] Moving messages received prior to " $threshold.ToString("D")
foreach ($m in $messages) {
if ($m.Subject.Length -gt 40) {
$subject = $m.Subject.Substring(0, 40)+"..."
} else {
$subject = $m.Subject
}
$date = $m.ReceivedTime
if ($date -ge $threshold) {
#Write-ColorText -Gray "[•] Skipping " -White $subject -Gray " received " $date.ToString("s")
continue
}
$year = $date.ToString("yyyy")
if ($yearFolder.Name -ne $year) {
$yearFolder = $archiveFolder.Folders.Item($year)
Write-ColorText -Gray "[•] Found Archive for " -White $year
}
$month = $date.ToString("yyyy-MM")
if ($monthFolder.Name -ne $month) {
$monthFolder = $yearFolder.Folders.Item($month)
Write-ColorText -Gray "[•] Found Archive for " -White $month
}
$updated = $m.Move($monthFolder)
Write-ColorText -Green "[✓]" -White " Moved " -Green $subject -White " received " -Green $date.ToString("s") -White " from " -Green $m.SenderName -White " to " -Green $month
}
# Closely based on code from Stack Overflow
# see https://stackoverflow.com/a/30265949/30280
function Write-ColorText
{
# DO NOT SPECIFY param(...)
# we parse colors ourselves.
$allColors = (
"-Black", "-DarkBlue","-DarkGreen","-DarkCyan","-DarkRed","-DarkMagenta","-DarkYellow","-Gray",
"-Darkgray","-Blue", "-Green", "-Cyan", "-Red", "-Magenta", "-Yellow", "-White",
"-Foreground"
)
$color = "Foreground"
$nonewline = $false
foreach($arg in $args)
{
if ($arg -eq "-nonewline")
{
$nonewline = $true
}
elseif ($allColors -contains $arg)
{
$color = $arg.substring(1)
}
elseif ($color -eq "Foreground")
{
Write-Host $arg -nonewline
}
else
{
Write-Host $arg -foreground $color -nonewline
}
}
Write-Host -nonewline:$nonewline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment