How to iterate through Exchange/Office365 mailbox to extract attachments by using Powershell

The below code will iterate through the logged on user’s mailbox and extract attachments that has CSV in the filename. It will then save the attachment on disk with a prepended random number (this is useful if you’re using this for automation where you keep getting CSVs using the same file name)

$o = New-Object -comobject outlook.application
$n = $o.GetNamespace("MAPI")
$f = $n.GetDefaultFolder(6) #6 is Inbox
$msgs = $f.Folders.Item("Subfolder_Name") #this needs to be under Inbox!
$msgs_archive = $f.Folders.Item("Subfolder_Name_Archived")
$filepath = "C:\location\where\attachments\will\be\saved\"

while ($msgs.Items.Count -gt 0) {
    $msgs.Items | foreach {
            $_.attachments | foreach {
                $rand = Get-Random
                $a = $_.filename
                If ($a.Contains("csv")) {
                    $_.saveasfile((Join-Path $filepath "$rand.$a"))