Using Graph for PowerShell, move email messages from one folder to another

Scenario: Lets say you accidentally deleted the messages from your Inbox, and now they are mixed in with your Deleted Items. Here are a couple Graph commands you run via PowerShell to move data back to your Inbox without doing it via the email client.

Resolution:

#Connect to Graph, if you need to install:  Install-Module Microsoft.Graph -scope AllUsers
Connect-MgGraph

#Variables:
#1. Create Variables
$email = "steve@domain.com"
$folders = get-mgusermailfolder -userid $email -PageSize 999
$Folder_DI = $folders | where displayname -eq "Deleted Items" | Select -ExpandProperty Id
$Folder_In = $folders | where displayname -eq "Inbox" | Select -ExpandProperty Id
$count = 0
$messages = $null
$DaysRange = (Get-Date).AddDays(-2)
$time = Get-Date ($DaysRange).ToUniversalTime() -UFormat '+%Y-%m-%dT%H:%M:%S.000Z'





#2. Loop through and move messages with modifieddate gt 3/4/2024

do
{
$count++
Write-Host "Pass Count: $Count"

$Messages = Get-MgUserMailFolderMessage -UserId $email -MailFolderId $folder_DI -filter "LastModifiedDateTime ge $time"
"Message Count:$($messages.count)"

#Move messages
$messages | %{
$i = $_.id
Move-MgUserMessage -MessageId $i -UserId $email -DestinationId $folder_in
}

}until ($Messages -eq $null)

Leave a comment