PowerShell – Zip Files and Send Email with Attachment

Hi Guys…

Suppose, you have below requirements:

1. To create a zip file containing all txt and dll files from a particular folder

2. To send the above newly created Zip file to the respective person in an email as an attachment.


I have achieved it by creating the below script: Here in the script, I created two functions – CreateZip and SendEmail.

Script Body –


   Create Zip file and then sent it as attachment in an email.
   This script will create a zip file and then will send this zip file as an attachment to an email.

#Script Name – SendEmailWithZipAttachment.ps1
#Creator – Mohd Aslam Ansari
#Date – 30-Dec-15
#Updated – First Version
#References, if any

$LogSource = "C:\temp\"
$ZipFileName = "Log.zip"

CreateZip $LogSource $ZipFileName

Function CreateZip {

New-Item -Force -ItemType directory -Path $LogSource\temp
Get-ChildItem $LogSource\* -Include *.txt,*.dll | ForEach-Object {Copy-Item $_ $LogSource\temp}

if (Test-Path -path $LogSource$ZipFileName)
    Remove-Item -Force $LogSource$ZipFileName

Add-Type -AssemblyName "System.IO.Compression.FileSystem"
[System.IO.Compression.ZipFile]::CreateFromDirectory($LogSource+’temp’, $LogSource+$ZipFileName)

Remove-Item -Force -Recurse $LogSource\temp

Function SendEmail {

$Email = New-Object -ComObject "CDO.Message"
http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
http://schemas.microsoft.com/cdo/configuration/smtpserver") = ‘xyz.smtp.com’
http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

$Email.Subject="Test email"
$Email.TextBodyPart = "PFA…"


—End of Article—


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s