We help IT Professionals succeed at work.

Powershell - help getting email/csv format

This script, I have a simple email sending in the subject and body.  What I need help with is getting the email into a html format in the body (I have the code below for an example, but don't know how to do it with this script).  I'd also like to add the user this is being run by, like in the example, and also add to the .csv this is writing to.  Currently the csv lists:  Computer | ExactTime

$OutArray = @()
workflow foreachrerun {
    param([string[]]$computers)
    foreach –parallel ($computer in $computers) {
       InlineScript {
Function Start-CCMRerunAdvertisement {
    [CmdLetBinding()]Param(
        [Parameter(Mandatory=$true)][string]$computerName,
        [Parameter(Mandatory=$false)][string]$advertisementId = "*",
        [Parameter(Mandatory=$false)][string]$packageId = "*",
        [Parameter(Mandatory=$false)][int]$maxRun = 1
        #[Parameters(Mandatory=$false)][switch]$moreThanPing = $false
    )
    if($advertisementId -eq "*" -and $packageId -eq "*") {
        Write-Error "You must supply either an AdvertisementID or a PackageID"
        return "Missing Parameters"
        break
    }
    $searchString = "$advertisementId-$packageId-*" 
    if(!(Test-Connection -ComputerName $computername -ErrorAction SilentlyContinue)) {
        if($moreThanPing) { 
            if(!(Get-ChildItem "\\$computername\c$" -ErrorAction SilentlyContinue)) {
                Write-Error "System Offline"
                Return "System Offline"
                break
            }
        } else {
            Return "$Computername is Offline"
            break
        }
    }
    Write-Verbose "Getting ID of ScheduleMessage on $computername"
    $schMsgs = Get-WmiObject -ComputerName $computername -Namespace "root\ccm\policy\machine\actualconfig" -Class CCM_Scheduler_ScheduledMessage
    $thisMsg = $schMsgs | ? { $_.ScheduledMessageID -like $searchString } | Sort ActiveTime -Descending | select -First $maxRun
    if(!$thisMsg) {
        Write-Verbose "Cannot Find Advertisement/Package on Target Computer"
        Return "Cannot Find Advertisment"
        break
    }
    $thisMsg | % {
        [xml]$activeMessage = $_.activeMessage
        $amProgramId = $activeMessage.SoftwareDeploymentMessage.ProgramID
        $amAdvId = $activeMessage.SoftwareDeploymentMessage.AdvertisementID
        $amPkgId = $activeMessage.SoftwareDeploymentMessage.PackageID
        $ScheduledMessageId = $_.ScheduledMessageId
        Write-Verbose  "Restarting $amArogramId (ADV=$amAdvId) (PKG=$amPkgId) for Schedule Message $ScheduledMessageId"
        $softwareDist = Get-WmiObject -ComputerName $computername -Namespace "root\ccm\policy\machine\actualconfig" -Class CCM_SoftwareDistribution -Filter "ADV_AdvertisementID = '$amAdvId' and PKG_PackageID = '$amPkgId'"
        $original_Rerun = $softwareDist.ADV_RepeatRunBehavior
        if($original_Rerun -ne "RerunAlways") {
            write-verbose "Changing Rerun Status from $original_Rerun to RerunAlways"
            $softwareDist.ADV_RepeatRunBehavior = "RerunAlways"
            $softwareDist.put() | Out-Null
        }
        Write-Verbose "Triggering Schedule on $computername"
        Invoke-WmiMethod -ComputerName $computername -Namespace "root\ccm" -Class "SMS_CLIENT" -Name TriggerSchedule $ScheduledMessageId | Out-Null
        Write-Verbose "Sleeping for 5 seconds"
        Start-Sleep -Seconds 5
        if($original_Rerun -ne "RerunAlways") {
            Write-Verbose "Changing Rerun Status back to $original_Rerun"
            $softwareDist.ADV_RepeatRunBehavior = "$original_Rerun"
            $softwareDist.put() | Out-Null
        }
        Return "Advert Reran on succesfully on $computername"
    }
}
function Send-EmailOffline {
    Send-MailMessage -From “admin@domain.com" -To "admin1@domain.com" -SMTPServer mail.domain.com -Subject “$($computername) is Offline" -Body "$($ComputerName) is Offline, please power on and re-run script."
}
function Send-EmailKickit {
    Send-MailMessage -From “admin@domain.com" -To "admin1@domain.com" -SMTPServer mail.domain.com -Subject “$($computername) Completed." -Body "$($ComputerName) Completed and is rebooting."
}
function Test-MyConnection {
    param (
        [Parameter(Mandatory=$true)]
        [System.String]
        $ComputerName
    )
    if (Test-Connection $computername -Quiet -Count 2) {
        Write-Output "Ping successful on $($computerName)"      
        Test-Running -ComputerName $ComputerName 
    }
    else {
        Send-EmailOffline -ComputerName $computername   
    }
  }   
function Test-Running {
    param (
        [Parameter(Mandatory=$true)]
        [System.String]$ComputerName
    )
$processList = @'
	"Name",				"Expected",		"Running"
	"cmd",				"1",			"0"
	"TrustedInstaller",	"1",			"0"
    "TIWorker",		    "1",			"0"
	"OfficeClickToRun",	"2",			"0"
'@ | ConvertFrom-Csv | ForEach-Object {$_.Expected = [int]$_.Expected; $_}
    $splat = @{}
    $splat['ComputerName'] = $computerName
    #Write-Output "Monitoring processes on $($computerName)" 
    Do  {
      $processList | ForEach-Object {
          $_.Running = @(Get-Process $_.Name @splat -ErrorAction SilentlyContinue).Count
      }
      ($processList | Format-Table -AutoSize | Out-String).Split("`r`n", [StringSplitOptions]::RemoveEmptyEntries) | Write-Output
      If ($running = @($processList | Where-Object {$_.Running -ge $_.Expected}).Count) {
          Start-Sleep -Seconds 5
      }
      Write-Output "Monitoring processes on $($computerName)" 
    } Until (-not $running)
    Send-EmailKickit -ComputerName $computername 
    $Today = (Get-Date).ToString('MM-dd-yyyy'),
    $ExactTime = Get-Date -Format "MM-dd-yyyy HHmm tt"
    $Logfile = "c:\input\Log.csv"
    $myobj = "" | Select "Computer", "ExactTime"
    $myobj.Computer = $ComputerName
    $myobj.ExactTime = $($(Get-Date).ToString('yyyy-MM-dd::hh:mm:ss'))

    $OutArray += $myobj
    $OutArray | Export-Csv $Logfile -NoTypeInformation -Append 
    Return "Process count finished on $computername"
} 
            Start-CCMRerunAdvertisement –ComputerName $using:Computer -AdvertisementID "TMC73737" 
            Test-MyConnection -ComputerName $using:Computer
        }
    }
}
$ComputerList  = Get-Content "c:\input\computerlist.txt"
foreachrerun -Computers $ComputerList 

Open in new window


Here is the script I have html output working:

$EnterpriseAdd = Get-ADGroup -Identity $UserEnt -Property Member | Select-Object -ExpandProperty Member
$LightRemove = Get-ADGroup -Identity $UserLight -Property Member | Select-Object -ExpandProperty Member
$Premium = Get-ADGroup -Identity $UserPremium -Property Member | Select-Object -ExpandProperty Member 

$dtFormat = 'yyyy-MM-dd HH:mm:ss'
$runningUser = & whoami.exe

$results = Import-Csv -Path $inputfile | ForEach-Object {
    If ($adUser = Get-ADUser -Filter "samAccountName -eq '$($_.Samaccountname)'") {
	    $adUser | Select-Object -Property  UserPrincipalName, @{n='Time'; e={Get-Date -Format $dtFormat}}, @{n='Group'; e={$UserPremium}}, @{n='Action'; e={'Override Group'}}, @{n='Administrator'; e={$runningUser}}
		$out = $adUser | Select-Object -Property UserPrincipalName, @{n='Time'; e={Get-Date -Format $dtFormat}}, @{n='Group'; e={$UserEnt}}, @{n='Administrator'; e={$runningUser}}, Action
		If ($Premium -contains $adUser.distinguishedName) {
		       $override = ' (override)'
			If ($EnterpriseAdd -contains $adUser.distinguishedName) {
				Remove-ADGroupMember -Identity $UserEnt -Members $adUser.distinguishedName -Confirm:$false  
				Write-Host -ForegroundColor Magenta " $($adUser.UserPrincipalName) removed from $($UserEnt) successfully"  
				$out.Action = "Removed$($override)"
			} Else {
				Write-Host -ForegroundColor Cyan " $($adUser.UserPrincipalName) is not a member of $($UserEnt)"  
				$out.Action = "NoMember$($override)"
			}
		} Else {
			$override = ''
			If ($EnterpriseAdd -contains $adUser.distinguishedName) {
				Write-Host -ForegroundColor Cyan " $($adUser.UserPrincipalName) is already a member of $($UserEnt)"  
				$out.Action = 'Existing'
			} Else {
				Add-ADGroupMember -Identity $UserEnt -Members $adUser.distinguishedName 
				Write-Host -ForegroundColor Green " $($adUser.UserPrincipalName) added to $($UserEnt) successfully"  
				$out.Action = 'Added'
			}
		}
		$out
		$out = $adUser | Select-Object -Property UserPrincipalName, @{n='Time'; e={Get-Date -Format $dtFormat}}, @{n='Group'; e={$UserLight}}, @{n='Administrator'; e={$runningUser}}, Action
		If ($LightRemove -contains $adUser.distinguishedName) {
			Remove-ADGroupMember -Identity $UserLight -Members $adUser.distinguishedName -Confirm:$false  
			Write-Host -ForegroundColor Magenta " $($adUser.UserPrincipalName) removed from $($UserLight) successfully"  
			$out.Action = "Removed$($override)"
		} Else {
			Write-Host -ForegroundColor Cyan " $($adUser.UserPrincipalName) is not a member of $($UserLight)"  
			$out.Action = "NoMember$($override)"
		}
		$out
	} Else {
         Write-Warning "User '$($_)' does not exist!"
		"User '$($_)' did not exist." | Add-Content -Path $logFile
	}
}
If ($results) {
	$results | Export-Csv -NoTypeInformation -Append -Path $outFile
}

$SmtpServer = "mail.domain.com"
$SmtpFrom = "admin@domain.com"
$SmtpTo =  @("user1@domain.com")
$SmtpCc =  @("user2@domain.com") 


$SmtpSubject = "Report"

$reporthtml = $results | ConvertTo-Html -fragment
  $htmlhead=$htmlhead="<html>
				<style>
				BODY{font-family: Arial; font-size: 8pt;}
				H1{font-size: 18px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
				H2{font-size: 18px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
				H3{font-size: 16px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
				H4{font-size: 12px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
				TABLE{border: 1px solid black; border-collapse: collapse; font-size: 8pt;}
				TH{border: 1px solid #969595; background: #dddddd; padding: 5px; color: #000000;}
				TD{border: 1px solid #969595; padding: 5px; }
				td.pass{background: #B7EB83;}
				td.warn{background: #FFF275;}
				td.fail{background: #FF2626; color: #ffffff;}
				td.info{background: #85D4FF;}
				</style>
				<body> 
                <h1 align=""Left"">Upgrade results</h1>"

  $htmltail = "</body> <br>

Upgrade.s.<br><br>

Contact admin with any questions.<br><br>            
  <br><br>"

  $htmlreport = $htmlhead + $reporthtml + $htmltail 

 Send-MailMessage -From $SmtpFrom -To $SmtpTo -Cc $SmtpCc -Bc $SmtpBc -Subject $SmtpSubject -SmtpServer $SmtpServer -bodyashtml -Body $htmlreport

Open in new window

Comment
Watch Question

Author

Commented:

found own solution

found own solution

Senior IT System EngineerSenior Systems Engineer
CERTIFIED EXPERT

Commented:
What was the solution Ron?
care to share it here.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.