POwershell error

Hello,

I already had some help about this code but I did not find how to resolve this lastest error.

Please see below full script

[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='chris@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="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
  }
  $att = Get-ChildItem $Resultpath -Filter "longfiles of *" | select -Expand FullName

  if ($att)   { $email += $att } 
  
  Send-MailMessage @email 
  Sleep -Milliseconds 200
}
elseif ($SaveReport)
{
  $HTMLMessage | Out-File $ReportName
}
else
{
   Return $HTMLmessage
}
#endregion General System Report

Open in new window


I get an error when the email is sent if the attachment exists.

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

Open in new window



below the part of code where the error is I think.

 $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


 

Thank you in advance for your help

Best,

Christophe
ChristopheIT CoordinatorAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sirbountyCommented:
Those are key-value pairs, try using this:
if ($att)  {$email += @{'Attachment'=$att}}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
That's correct. Sorry for that - it was my modification causing this error. I had tested it that way :/.
ChristopheIT CoordinatorAuthor Commented:
Hello Qlemo,

No problem at all. You already did a very good work for me ;-)

Thanks
ChristopheIT CoordinatorAuthor Commented:
Very nice work. It is working now.

Thank you

Best,

Christophe
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.