Change File Extension and Email File

This topic contains 1 reply, has 2 voices, and was last updated by  Richard Siddaway 3 years, 9 months ago.

  • Author
    Posts
  • #12579

    totaln00b
    Participant

    Hiya,

    I wonder if anyone can assist please? I'm using a switch to evaluate a condition which is all working quite nicely at the moment i.e. it sends me an email alert when a condition is met (that a file has been created which is more than 816 bytes). However, I'd like to add some more functionality. What I'd like to do is email the file (that is over 816 bytes). Ideally, I'd also like to change the file extension. Currently the file has no file extension so I'd like to change it to a .txt. This is because the file will be going to and end user and I know they'll have issues if they have to save it and change the extension themselves. If I were to do this myself I'd probably copy the file (to a new location), change the extension, email it (as an attachment) then drop the file (as I don't need it once it has been emailed). However, I suspect that someone with more knowledge than me can suggest a method that is less messy.

    I've looked through the forum and I can see the code for adding attachments etc but I couldn't see anything that is super relevant to my query.

    Thanks in advance!

    My current code:

    $Now = [datetime]::Now.AddMinutes(-59)
    $Location = "D:\l\var\*"

    $Files = Get-ChildItem $Location * | where { $_.CreationTime -ge $Now -and $_.Length -gt 816 }
    #the above checks that it is older than 59 mins and is greater than 816 bytes as this is the size of the empty error file
    $EmailTo = 'abc@123.co.uk'
    $EmailSubject = 'TPIE'
    $EmailServer = '12.34.5.67'

    Function SendMail
    {
    Send-MailMessage -SmtpServer $EmailServer -From "Batch Alert " -To $EmailTo -Subject $EmailSubject -Body $html -BodyAsHtml -Priority 'high'
    }

    switch($errorcheck)
    {
    { $files }
    { $html = "

    TPIE

    "
    $html += "Error Message Detected in Spool File"
    $html += "

    An error was detected within the last hour for the TPI.

    "
    $html += $files | ConvertTo-Html -Fragment -as list
    $css = "

    "
    $html = $css + $html
    SendMail
    }

    default { "No Errors Detected" }
    }

  • #12620

    Richard Siddaway
    Moderator

    To be honest your method

    If I were to do this myself I'd probably copy the file (to a new location), change the extension, email it (as an attachment) then drop the file (as I don't need it once it has been emailed).

    is about as good as it gets. I'd do something similar. I guess the bit you are stuck with is changing the extension. The easiest way I think is to rename the file
    rename-item -Path testfile -NewName testfile.txt

You must be logged in to reply to this topic.