Created
February 19, 2018 20:08
-
-
Save davidsylvestre/65c70d0aa6048a946bbdb83d2df2d70b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## | |
| ## Source: https://chris.dziemborowicz.com/blog/2013/05/18/how-to-batch-extract-attachments-from-msg-files-using-powershell/ | |
| ## | |
| ## Instalation: | |
| ## | |
| ## On Windows Vista and newer, the PowerShell modules folder is typically found here: | |
| ## C:\Users\__your_username__\Documents\WindowsPowerShell\Modules | |
| ## | |
| ## On Windows XP, the PowerShell modules folder is typically found here: | |
| ## C:\Documents and Settings\__your_username__\Documents\WindowsPowerShell\Modules | |
| ## | |
| ## Usage: | |
| ## Import-Module MsgUtility | |
| ## Expand-MsgAttachment * | |
| ## | |
| ## | |
| function Expand-MsgAttachment | |
| { | |
| [CmdletBinding()] | |
| Param | |
| ( | |
| [Parameter(ParameterSetName="Path", Position=0, Mandatory=$True)] | |
| [String]$Path, | |
| [Parameter(ParameterSetName="LiteralPath", Mandatory=$True)] | |
| [String]$LiteralPath, | |
| [Parameter(ParameterSetName="FileInfo", Mandatory=$True, ValueFromPipeline=$True)] | |
| [System.IO.FileInfo]$Item | |
| ) | |
| Begin | |
| { | |
| # Load application | |
| Write-Verbose "Loading Microsoft Outlook..." | |
| $outlook = New-Object -ComObject Outlook.Application | |
| } | |
| Process | |
| { | |
| switch ($PSCmdlet.ParameterSetName) | |
| { | |
| "Path" { $files = Get-ChildItem -Path $Path } | |
| "LiteralPath" { $files = Get-ChildItem -LiteralPath $LiteralPath } | |
| "FileInfo" { $files = $Item } | |
| } | |
| $files | % { | |
| # Work out file names | |
| $msgFn = $_.FullName | |
| # Skip non-.msg files | |
| if ($msgFn -notlike "*.msg") { | |
| Write-Verbose "Skipping $_ (not an .msg file)..." | |
| return | |
| } | |
| # Extract message body | |
| Write-Verbose "Extracting attachments from $_..." | |
| $msg = $outlook.CreateItemFromTemplate($msgFn) | |
| $msg.Attachments | % { | |
| # Work out attachment file name | |
| $attFn = $msgFn -replace '\.msg$', " - Attachment - $($_.FileName)" | |
| # Do not try to overwrite existing files | |
| if (Test-Path -literalPath $attFn) { | |
| Write-Verbose "Skipping $($_.FileName) (file already exists)..." | |
| return | |
| } | |
| # Save attachment | |
| Write-Verbose "Saving $($_.FileName)..." | |
| $_.SaveAsFile($attFn) | |
| # Output to pipeline | |
| Get-ChildItem -LiteralPath $attFn | |
| } | |
| } | |
| } | |
| End | |
| { | |
| Write-Verbose "Done." | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment