简体   繁体   中英

Create attachment array for sending email

I have to send email and attach files which are having more than 4 lines as content.

$Final_File_list = Get-ChildItem -Path "E:\files" -Filter "New_*.txt"

foreach($NewFile in $Final_File_list)
{
    $Full_File_Path = $NewFile.FullName
    $GetLines = (Get-Content -Path $Full_File_Path | Measure-Object -Line).Lines

    if($GetLines -gt 4)
    {
        [array]$rn_all+=$Full_File_Path+"," #$Full_File_Path -join ','
    }
}

Please let me know how add multiple files as attachment in this case.

I think you were very close already.

Try

$Final_File_list = Get-ChildItem -Path "E:\files" -Filter "New_*.txt"

$attachments = foreach($NewFile in $Final_File_list) {
    if (@(Get-Content -Path $NewFile.FullName).Count -gt 4) {
        # simply output the FullName so it gets collected in variable $attachments
        $NewFile.FullName
    }
}

if ($attachments) {
    # send your email
    $mailParams = @{
        From        = 'you@yourcompany.com'
        To          = 'someone@yourcompany.com'
        Subject     = 'PortErrors'
        Body        = 'Please see the attached files'
        SmtpServer  = 'smtp.yourcompany.com'
        Attachments = $attachments
        # more parameters go here
    }
    # send the email
    Send-MailMessage @mailParams
}

PS If the files can be large, you can speed up a little if you add parameter -TotalCount to the Get-Content line, so it stops when it reads more than 4 lines max:

if (@(Get-Content -Path $NewFile.FullName -TotalCount 5).Count -gt 4) {
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM