Skip to content

Instantly share code, notes, and snippets.

@njm2112
Forked from dziemborowicz/Remove-MsgAttachment.ps1
Last active December 2, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njm2112/9325f949dcb5536979b11c230993dc0f to your computer and use it in GitHub Desktop.
Save njm2112/9325f949dcb5536979b11c230993dc0f to your computer and use it in GitHub Desktop.
PowerShell cmdlet for removing attachments from *.msg files
function Remove-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
{
# OlInspectorClose constants
$olSave = 0
$olDiscard = 1
$olPromptForSave = 2
# OlSaveAsType constants
$olTXT = 0
$olRTF = 1
$olTemplate = 2
$olMSG = 3
$olDoc = 4
# 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
}
# Open the msg file
$msg = $outlook.Session.OpenSharedItem($msgFn)
# Do not touch files without attachments
if ($msg.Attachments.Count -eq 0) {
Write-Verbose "Skipping $_ (has no attachments)..."
$msg.Close($olDiscard)
return
}
# Clone message
$msgCopy = $msg.Copy()
$msg.Close($olDiscard)
# Remove attachments from message
Write-Verbose "Removing attachments from $_..."
while ($msgCopy.Attachments.Count -gt 0) {
$msgCopy.Attachments.Remove(1)
}
# Save message
$msgCopy.SaveAs($msgFn, $olMSG)
}
}
End
{
Write-Verbose "Done."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment