Last active
December 30, 2021 18:38
-
-
Save dziemborowicz/145061dc9a308a37526a to your computer and use it in GitHub Desktop.
PowerShell cmdlet for removing attachments from *.msg files
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
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
No worries. Any time. :)
If you unwrap everything in the .ps1 file so that it's not enclosed in a
function
, then I think you can run the script directly as you were doing it (without having toImport-Module
first).That is, if you change --
to --
in the
Remove-MsgAttachment.ps1
file.