Karamzov
Karamzov

Reputation: 403

Powershell to send EMAIL attaching last modified file details?

I am trying to create a PowerShell which can search folder and send mail for the last created file details for filename and size , The email part is working fine but i am unable to attach file size and name in the body

Set-Location Y:\It-dept\OracleBkp
$latest = Get-Childitem -file $path | Sort LastWriteTime -Descending | select -First 1
$size = Get-Childitem -file $latest | Select-Object Name, @{Name="MegaBytes";Expression={$_.Length / 1MB}}
$Username  = "<sender email>"
$EmailPassword = "<password>"
$EmailTo = <Receiver Mail> 
$EmailFrom   = <Sender EMail>
$Subject = Oracle Backup 
$Body=  $latest
$Body += $size
$SMTPServer  = "smtp.outlook.com"  
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body) 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword) 
$SMTPClient.Send($SMTPMessage)

The above is sending an email with filename but size is not showing in the body. Any support will be appreciated..Thanks in advance

Upvotes: 0

Views: 540

Answers (1)

postanote
postanote

Reputation: 16106

Why not just do this...

$TargetPath = 'C:\Temp\OracleBkp.txt'

$latest = Get-Childitem -file $TargetPath | 
Sort-Object -Property LastWriteTime -Descending | 
Select-Object Name, @{
    Name       = 'MegaBytes'
    Expression = {$PSItem.Length / 1MB}
} -First 1
# Results
<#
Name          MegaBytes
----          ---------
OracleBkp.txt         0
#>

$Username               = 'sender emai'
$EmailPassword          = '<password'
$EmailTo                = 'Receiver Mail'
$EmailFrom              = 'Sender EMail'
$Subject                = 'Oracle Backup'
$Body                   = "File details `n $latest"
$SMTPServer             = 'smtp.outlook.com'
$SMTPMessage            = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$SMTPClient             = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl   = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword)
$SMTPClient.Send($SMTPMessage)

Upvotes: 1

Related Questions