We help IT Professionals succeed at work.
Get Started

Powershell email. merge 2 scripts

Christophe asked
Last Modified: 2015-04-24

I have found a script to find files with long path. This script sends an email with attachment (files list). It works very nice. I would like to include this script into one I already use for others actions and I do not know how to include the first script to the second. I'd like to have the attachment with the email sent by the second script. The second script works very well also.

The first script to find files with long paths:
$limit = 150
$testpath = "c:\users\$env:username\"
$resultpath = "c:\outputtemp"
$admins = "myemail"
$from = "myemail"
$smtpserver = "myserver"

Get-ChildItem -Path $testpath -Recurse | ?{$_.fullname.length -gt $limit} | 
	Select-Object fullname, 
		@{n="namelength"; e={$_.fullname.length}} | 
	Out-File -FilePath "$resultpath\Longfiles of $($env:username -replace "\\","-").txt" -Append -InputObject "$($_.namelength) - $($_.fullname)"
Get-ChildItem $resultpath -Filter "longfiles of *" | % {
	if($_.name -match "Longfiles\sof\s(.+)\.txt"){
		$user = $matches[1] -replace "-","\"
		$ntacc = New-Object System.Security.Principal.NTAccount($user)
		$sid = $ntacc.Translate([System.Security.Principal.SecurityIdentifier])
		$aduser = [ADSI]"LDAP://<SID=$sid>"
		$email = $aduser.Properties.mail
		if($email) {Send-MailMessage -Attachments $_.fullname `
			-From $from -SmtpServer $smtpserver -Subject "System notice" -To $email
		else {
			Send-MailMessage -Attachments $_.fullname -Body "email coudn't be sent to owner" `
			-From $from -SmtpServer iqjb-exchback -Subject "System notice" -To $admins
	else {Write-Host "Some error with file $_"}

Open in new window

The second script where I want to include the first:
	[Alias('Server Name')]
	[Alias('Email Relay')]
	[String]$EmailRelay = "myserver",		
	[Alias('Email Sender')]
	[String]$EmailSender="$env:username" + "@test.com",
	[Alias('Email Recipient')]
	[Alias('Send Mail')]
#endregion Parameters

#region Configuration
## Environment Specific - Change These ##
$EventNum = 3         # Number of events to fetch for system report
$ProccessNumToFetch = 10   # Number of processes to fetch for system report

## Required - Leave These Alone ##
# System and Error Report Headers
$HTMLHeader = @'
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Frameset//EN' 'http://www.w3.org/TR/html4/frameset.dtd'>
<html><head><title>My Systems Report</title>
<style type='text/css'>
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;

    #report { width: 450px; }

   border-collapse: collapse;
   border: none;
   font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
   color: black;
   margin-bottom: 10px;
   table td{
   font-size: 12px;
   padding-left: 0px;
   padding-right: 20px;
   text-align: left;
   table th {
   font-size: 12px;
   font-weight: bold;
   padding-left: 0px;
   padding-right: 20px;
   text-align: left;

h2{ clear: both; font-size: 130%; }

   clear: both;
   font-size: 105%;
   margin-left: 20px;
   margin-top: 30px;

p{ margin-left: 20px; font-size: 12px; }

table.list{ float: left; }
   table.list td:nth-child(1){
   font-weight: bold;
   border-right: 1px grey solid;
   text-align: right;

table.list td:nth-child(2){ padding-left: 7px; }
table tr:nth-child(even) td:nth-child(even){ background: #CCCCCC; }
table tr:nth-child(odd) td:nth-child(odd){ background: #F2F2F2; }
table tr:nth-child(even) td:nth-child(odd){ background: #DDDDDD; }
table tr:nth-child(odd) td:nth-child(even){ background: #E5E5E5; }
div.column { width: 450px; float: left; }
div.first{ padding-right: 20px; border-right: 1px  grey solid; }
div.second{ margin-left: 30px; }
table{ margin-left: 20px; }

$HTMLEnd = @'

# Date Format
$DateFormat      = Get-Date -Format "MM/dd/yyyy_HHmmss" 

# Monitor

$Monitormodel = Get-WmiObject -Namespace "Root\WMI" -Query "Select * FROM WMIMonitorID" | Select-Object -Property `
	@{Name=" "; Expression={[System.Text.Encoding]::Ascii.GetString($_.UserFriendlyName)}} |
    Format-table |

$Monitorserial = Get-WmiObject -Namespace "Root\WMI" -Query "Select * FROM WMIMonitorID" | Select-Object -Property `
	@{Name=" "; Expression={[System.Text.Encoding]::Ascii.GetString($_.SerialNumberID)}} |
    Format-table |

# Folder size
$size = "{0:N2}" -f ( ( Get-ChildItem u:\$env:username\Backup\ -Recurse -Force | Measure-Object -Property Length -Sum ).Sum / 1GB ) |

#region Functions
Function Get-DriveSpace() 
   Param (

   $Title="Drive Report"

   #define an array for html fragments

   #get the drive data
   $data=get-wmiobject -Class Win32_logicaldisk -filter "drivetype=3" -computer $computers

   #group data by computername
   $groups=$Data | Group-Object -Property SystemName

   #this is the graph character

   #create html fragments for each computer
   #iterate through each group object
   ForEach ($computer in $groups) {
       #define a collection of drives from the group object
       #create an html fragment
       $html=$drives | Select @{Name="Drive";Expression={$_.DeviceID}},
       @{Name='Used GB';Expression={"{0:N2}" -f (($_.Size - $_.Freespace)/1GB) }},
       @{Name='Free GB';Expression={"{0:N2}" -f ($_.FreeSpace/1GB) }},
	   @{Name='% Free';Expression={"{0:N2}" -f (($_.FreeSpace/$_.Size)*100)}},
         $UsedPer= (($_.Size - $_.Freespace)/$_.Size)*100
         $UsedGraph=$g * ($UsedPer/2)
         $FreeGraph=$g* ((100-$UsedPer)/2)
         #I'm using place holders for the < and > characters
         "xopenFont color=Redxclose{0}xopen/FontxclosexopenFont Color=Greenxclose{1}xopen/fontxclose" -f $usedGraph,$FreeGraph
       }} | ConvertTo-Html -Fragment 
       #replace the tag place holders. It is a hack but it works.
       $html=$html -replace "xopen","<"
       $html=$html -replace "xclose",">"
       #add to fragments
       #insert a return between each computer
   } #foreach computer

   #write the result to a file
   Return $fragments

#region General System Report
$DriveSpaceReport = Get-DriveSpace $ServerName
$CurrentSystemHTML = ''
$CurrentSystemHTML += "<hr noshade size=3 width='100%'>"
$CurrentSystemHTML += "<div id='report'>"
$CurrentSystemHTML += "<p>Hi</p>"
$CurrentSystemHTML += "<p>You receive this email because Backup/Restore action is finished for <b><span style='color:#a10a0a'>$env:username</span></b></p>"
$CurrentSystemHTML += "<h3>User information</h3>"
$CurrentSystemHTML += '<table class="list">'
$CurrentSystemHTML += '<tr>'
$CurrentSystemHTML += '<td>Login:</td>'
$CurrentSystemHTML += "<td><span style='color:#a10a0a'>$env:username</span></td>"
$CurrentSystemHTML += "</tr>"
$CurrentSystemHTML += "<tr>"
$CurrentSystemHTML += '<td>Computer name:</td>'
$CurrentSystemHTML += "<td><span style='color:#a10a0a'>$env:computername</span></td>"
$CurrentSystemHTML += "</tr>"
$CurrentSystemHTML += "<tr>"
$CurrentSystemHTML += '<td>Monitor(s):</td>'
$CurrentSystemHTML += "<td>Model:<span style='color:#a10a0a'>$Monitormodel</span></td>"
$CurrentSystemHTML += "<td>Serial number:<span style='color:#a10a0a'>$Monitorserial</span></td>"
$CurrentSystemHTML += "</tr>"
$CurrentSystemHTML += "</table>"
$CurrentSystemHTML += "<h3>User PC local disks information</h3>"
$CurrentSystemHTML += "$DriveSpaceReport"
$CurrentSystemHTML += "<tr>"
$CurrentSystemHTML += "<h3>Backup information</h3>"
$CurrentSystemHTML += "<p>User backup folder size is <span style='color:#a10a0a'>$size Gb</span></p>"
$CurrentSystemHTML += "</tr>"
$CurrentSystemHTML += "<hr noshade size=3 width='100%'>"

# Add the current System HTML Report into the final HTML Report body
$HTMLMiddle += $CurrentSystemHTML

# Assemble the final report from all our HTML sections
$HTMLmessage = $HTMLHeader + $HTMLMiddle + $HTMLEnd

if ($SendMail)
	$HTMLmessage = $HTMLmessage | Out-String
		From = $EmailSender
		To = $EmailRecipient
		Subject = "Backup/Restore Report for: $env:username"
		SMTPServer = $EmailRelay
		Body = $HTMLmessage
		Encoding = ([System.Text.Encoding]::UTF8)
		BodyAsHTML = $true
	Send-MailMessage @email
	Sleep -Milliseconds 200
elseif ($SaveReport)
	$HTMLMessage | Out-File $ReportName
   Return $HTMLmessage
#endregion General System Report

Open in new window

Thank you in advance for your help

Watch Question
"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
This problem has been solved!
Unlock 1 Answer and 9 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE