Powershell email. merge 2 scripts

Hello,

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="owner";e={
			$_.GetAccessControl().GetOwner('System.Security.Principal.NTAccount')}},
		@{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:
[CmdletBinding()]
param
(
	[Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
	[AllowEmptyString()]
	[Alias('Server Name')]
	[String]$ServerName="$env:computername",				
	[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Relay')]
	[String]$EmailRelay = "myserver",		
	[Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Sender')]
	[String]$EmailSender="$env:username" + "@test.com",
	[Parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Recipient')]
	[String]$EmailRecipient='myemail',
	[Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Send Mail')]
	[Bool]$SendMail=$true,
	[Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Bool]$SaveReport=$false,
	[Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[String]$ReportName=".\GeneralSystemStatus.html"
)
#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; }

    table{
   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%; }

h3{
   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; }
-->
</style>
</head>
<body>
'@

$HTMLEnd = @'
</div>
</body>
</html>
'@

# 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 |
	Out-String

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

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


#region Functions
Function Get-DriveSpace() 
{
   Param (
   [string[]]$computers=@($env:computername)
   )

   $Title="Drive Report"

   #define an array for html fragments
   $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
   [string]$g=[char]9608 

   #create html fragments for each computer
   #iterate through each group object
           
   ForEach ($computer in $groups) {
       #define a collection of drives from the group object
       $Drives=$computer.group
       
       #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)}},
       @{Name="Usage";Expression={
         $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
       $Fragments+=$html
       
       #insert a return between each computer
       $fragments+="<br>"
       
   } #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
	$email= 
	@{
		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
}
else
{
   Return $HTMLmessage
}
#endregion General System Report

Open in new window


Thank you in advance for your help

Christophe
ChristopheIT CoordinatorAsked:
Who is Participating?
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
@#~! I should have considered that. Just replace that lines setting $email (lines 239-249) with:
 $email= 
  @{
    From = $EmailSender
    To = $EmailRecipient
    Subject = "Backup/Restore and Longfiles Report for: $env:username"
    SMTPServer = $EmailRelay
    Body = $HTMLmessage
    Encoding = ([System.Text.Encoding]::UTF8)
    BodyAsHTML = $true
  }
  $att = Get-ChildItem $Resultpath -Filter "longfiles of *" | select -Expand FullName
  if ($att)   { $email += $att } 

Open in new window

0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
That would be difficult, because the first script generates several output files.  It also alerts each respective user (the owner of those files), while the second script sends an alert to admins only.
0
 
ChristopheIT CoordinatorAuthor Commented:
Thanks for your answer and for have formatted my post. I did not know about the code blocks ;-)

The first script sends email with attachment to only one me. Second same.  I tought we can put email attachment from the first script (long path) in the email sent from the second script.
0
On-Demand: Securing Your Wi-Fi for Summer Travel

Traveling this summer?Check out our on-demand webinar to learn about the importance of Wi-Fi security and 3 easy measures you can start taking immediately to protect your private data while using public Wi-Fi. Follow us today to learn more!

 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
If the first script finds valid email addresses for the owner of the files, the mail is sent to them, otherwise to the single account provided as $admins.
0
 
ChristopheIT CoordinatorAuthor Commented:
Thanks. I remove that. I do not need that. I just want to receive the attachment if files with long path found. If not, not attachment in the email.

I remove the condition. and merge both scripts. It works but 2 emails are sent if files with long path found.

[CmdletBinding()]
param
(
	[Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
	[AllowEmptyString()]
	[Alias('Server Name')]
	[String]$ServerName="$env:computername",				
	[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Relay')]
	[String]$EmailRelay = "smtp.test.com",		
	[Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Sender')]
	[String]$EmailSender="$env:username" + "@test.com",
	[Parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Email Recipient')]
	[String]$EmailRecipient='christophe@test.com',
	[Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Alias('Send Mail')]
	[Bool]$SendMail=$true,
	[Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[Bool]$SaveReport=$false,
	[Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
	[String]$ReportName=".\GeneralSystemStatus.html"
)
#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; }

    table{
   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%; }

h3{
   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; }
-->
</style>
</head>
<body>
'@

$HTMLEnd = @'
</div>
</body>
</html>
'@

# 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 |
	Out-String

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

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

# long path
$limit = 150
$testpath = "c:\users\$env:username\"
$resultpath = "c:\outputtemp"


Get-ChildItem -Path $testpath -Recurse | ?{$_.fullname.length -gt $limit} | 
	Select-Object fullname, 
		@{n="owner";e={
			$_.GetAccessControl().GetOwner('System.Security.Principal.NTAccount')}},
		@{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
        Send-MailMessage -Attachments $_.fullname -From $EmailSender -SmtpServer $EmailRelay -Subject "System notice" -To $EmailRecipient
}		
}

#region Functions
Function Get-DriveSpace() 
{
   Param (
   [string[]]$computers=@($env:computername)
   )

   $Title="Drive Report"

   #define an array for html fragments
   $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
   [string]$g=[char]9608 

   #create html fragments for each computer
   #iterate through each group object
           
   ForEach ($computer in $groups) {
       #define a collection of drives from the group object
       $Drives=$computer.group
       
       #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)}},
       @{Name="Usage";Expression={
         $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
       $Fragments+=$html
       
       #insert a return between each computer
       $fragments+="<br>"
       
   } #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 Paris IT Team!</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 += "<p>Do not forget to update the inventory file!</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 += "<p>User backup folder can be found by clicking <a href=file://\\prstorage02\IT\ProfilesBackup\$env:username\Backup>here</a></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
	$email= 
	@{
		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
}
else
{
   Return $HTMLmessage
}
#endregion General System Report

Open in new window

0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
It is more like this:
[CmdletBinding()]
param
(
  [Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
  [AllowEmptyString()]
  [Alias('Server Name')]
  [String]$ServerName="$env:computername",        
  [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [Alias('Email Relay')]
  [String]$EmailRelay = "smtp.test.com",    
  [Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [Alias('Email Sender')]
  [String]$EmailSender="$env:username" + "@test.com",
  [Parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [Alias('Email Recipient')]
  [String]$EmailRecipient='christophe@test.com',
  [Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [Alias('Send Mail')]
  [Bool]$SendMail=$true,
  [Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [Bool]$SaveReport=$false,
  [Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
  [String]$ReportName=".\GeneralSystemStatus.html"
)
#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; }

    table{
   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%; }

h3{
   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; }
-->
</style>
</head>
<body>
'@

$HTMLEnd = @'
</div>
</body>
</html>
'@

# 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 |
  Out-String

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

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

#region Functions
Function Get-DriveSpace() 
{
   Param (
   [string[]]$computers=@($env:computername)
   )

   $Title="Drive Report"

   #define an array for html fragments
   $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
   [string]$g=[char]9608 

   #create html fragments for each computer
   #iterate through each group object
           
   ForEach ($computer in $groups) {
       #define a collection of drives from the group object
       $Drives=$computer.group
       
       #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)}},
       @{Name="Usage";Expression={
         $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
       $Fragments+=$html
       
       #insert a return between each computer
       $fragments+="<br>"
       
   } #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 Paris IT Team!</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 += "<p>Do not forget to update the inventory file!</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 += "<p>User backup folder can be found by clicking <a href=file://\\prstorage02\IT\ProfilesBackup\$env:username\Backup>here</a></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

# Get long path
$limit = 150
$testpath = "c:\users\$env:username\"
$resultpath = "c:\outputtemp"


Get-ChildItem -Path $testpath -Recurse | ?{$_.fullname.length -gt $limit} | 
  Select-Object fullname, 
    @{n="owner";e={
      $_.GetAccessControl().GetOwner('System.Security.Principal.NTAccount')}},
    @{n="namelength"; e={$_.fullname.length}} | 
%{
  Out-File -FilePath "$resultpath\Longfiles of $($env:username -replace "\\","-").txt" -Append -InputObject "$($_.namelength) - $($_.fullname)"
}

if ($SendMail)
{
  $HTMLmessage = $HTMLmessage | Out-String
  $email= 
  @{
    From = $EmailSender
    To = $EmailRecipient
    Subject = "Backup/Restore and Longfiles Report for: $env:username"
    SMTPServer = $EmailRelay
    Body = $HTMLmessage
    Encoding = ([System.Text.Encoding]::UTF8)
    BodyAsHTML = $true
    Attachments = (Get-ChildItem $Resultpath -Filter "longfiles of *" | select -Expand FullName)
  }
  
  Send-MailMessage @email
  Sleep -Milliseconds 200
}
elseif ($SaveReport)
{
  $HTMLMessage | Out-File $ReportName
}
else
{
   Return $HTMLmessage
}
#endregion General System Report

Open in new window

0
 
ChristopheIT CoordinatorAuthor Commented:
Thank you very much. It is very incredible!

Everything works except when the file txt does not exist because no files with long path were found, no email sent.

Is it possible to add a condition to continue to send email when the txt file does not exist?
0
 
ChristopheIT CoordinatorAuthor Commented:
Thank you very much for your help! You are an expert!
0
 
ChristopheIT CoordinatorAuthor Commented:
Sorry, I just tried and it does not work when attachment exists.

A hash table can only be added to another hash table.
At C:\Users\chd\Desktop\email256v2.ps1:250 char:17
+   if ($att)   { $email += $att }
+                 ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : AddHashTableToNonHashTable


I tried to correct that but I have not found solution.

Do you know how to correct that?

Thanks

Christophe
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.