I'm writing a little script that would batch convert .msg
files to .pdf
with .html
in the middle, all while saving attachments. While this is a work in progress I encountered a strange thing.
If a file with the same .fullname
as the attachment is already present in the folder it gets overwritten, no prompt.
Is there a way to force confirmation on .SaveAsFile
method for the attachments? See current script below.
$o = New-Object -ComObject outlook.application
$1 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
Set-Alias -Name chrome -Value $1
Get-ChildItem -file -filter *.msg | ForEach-Object {
$msgFullname = $_.FullName
$htmlname = $msgFullname -replace '.msg', '.html'
$attloc = $_.Directory
$msg = $o.CreateItemFromTemplate($msgFullname)
if ($msg.Attachments.Count -ge 1) {
$msg.Attachments | ForEach-Object {
$attname = $attloc.FullName + "\" + $_.FileName
$_.SaveAsFile($attname)
}
}
$msg.SaveAs($htmlname, 5)
$dest = $_.DirectoryName + "\" + $_.BaseName + ".pdf"
$source = $_.DirectoryName + "\" + $_.BaseName + ".html"
chrome --headless --disable-gpu --print-to-pdf=$dest $source --print-to-pdf-no-header
$1 = $_.BaseName
Get-ChildItem | Where-Object { ($_.PSIsContainer -eq $true -and $_.BaseName -like "*$1*") -OR $_.Name -like ($_.BaseName + "*.html") } | Remove-Item -Recurse -Force
}
As an answer I am presenting a modification of the script from the first post. In this, the script checks if a file with the same name as attachment is already present and if it is, another name is given. particularily a '-' and a number are added at the end.
$o = new-object -comobject outlook.application
$1 = "C:\Program Files\Google\Chrome\Application\chrome.exe"
Set-Alias -Name chrome -Value $1
function att_inc
{
$attname = $attloc.FullName + "\" + $_.FileName.substring(0,$_.Filename.Lastindexof('.')) + '-' + $counter + $_.FileName.substring($_.Filename.Lastindexof('.'))
main
}
gci -file -filter *.msg|%{
$msgFullname = $_.FullName
$htmlname = $msgFullname -replace '.msg', '.html'
$attloc = $_.Directory
$msg = $o.CreateItemFromTemplate($msgFullname)
if($msg.Attachments.Count -ge 1){
$msg.Attachments|%{
$counter = 0
$attname = $attloc.FullName + "\" + $_.FileName
function main {
if((test-path $attname) -eq $false){
$_.SaveAsFile($attname)
}
else {
$counter++
att_inc
}
}
main
}
}
msg.SaveAs($htmlname, 5)
$dest = $_.DirectoryName + "\" + $_.BaseName + ".pdf"
$source = $_.DirectoryName + "\" + $_.BaseName + ".html"
chrome --headless --disable-gpu --print-to-pdf=$dest $source --print-to-pdf-no-header
$1 = $_.BaseName
gci|?{($_.PSIsContainer -eq $true -and $_.BaseName -like "*$1*") -OR $_.Name -like ($_.BaseName + "*.html")}|remove-item -recurse -force
}