Home > Blockchain >  Powershell attach latest three files in a directory to an email
Powershell attach latest three files in a directory to an email

Time:03-16

can anyone assist in getting the latest three files in a directory to attach to an email? I'm currently only able to attach the single latest email with the below script. Also if it matters these emails will always have the same identifying keywords somewhere in the file name such as 1434343Apple20220314, 1434343orange20220314, 1434343pear20220314

$dir = "C:\Users\Downloads\"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$newfile = $latest.name



$FilePath = Join-Path $dir $newfile
$FileExists =  test-path $FilePath 

If ($FileExists -eq $True) {
$outlook = New-Object -comObject Outlook.Application 
$message = $outlook.CreateItem(0)
$message.Recipients.Add([email protected])
$message.Subject = "files"  
$message.Body = "this is test email"


$file = $FilePath
$message.Attachments.Add($file)
$message.Display()
Write-Host "File is emailed"
}
else
{write-host "No File Found"}

CodePudding user response:

I really am not that familiar with the Outlook ComObject, but here's some quick/dirty scripting:

$outlook = New-Object -comObject Outlook.Application 
$email   = "[email protected]"
$message = $outlook.CreateItem(0)
$message.Recipients.Add($email)
$message.Subject = "files"  
$message.Body = "this is test email"

$path    = "C:\Users\Downloads"
$lastest = Get-ChildItem -Path $path -File | Sort-Object -Property LastAccessTime -Descending | Select-Object -First 3
foreach ($file in $lastest)
{
    $message.Attachments.Add($file.FullName)
}

$message.Display()

Really, all you need is a loop which I incorporated into your existing code. At the moment, your current code doesn't make sense. Why?

  1. $FilePath would never return a path if $latest doesn't contain anything.

  2. $FileExists relies on $FilePath and as you could see from bullet 1., your Test-Path would be invalid to begin with. This would render your if() statement useless.

  • Related