## 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")) } }$_.Move(\$msgs_archive)
}
}

## Using Powershell to read Sysmon events

If you install Sysmon as a service, it will start logging events into Windows Event Log. These events are stored in a binary format; hence extraction is a bit tricky.

You can use Powershell to read these events using the following:

Get-WinEvent @{logname="Microsoft-Windows-Sysmon/Operational"} | Select-Object -Property TimeCreated,ID,Message -First 5 | Format-List

The above command and filters will show you the last 5 events logged. Bear in mind that what goes into this event log is controlled by Sysmon XML configuration file. Hence, if you’re not seeing something you’re expecting in the Windows Event Logs, you may need to tweak Sysmon configurations.