Good afternoon, we have a script that runs at x period of time. Its job is to get a set of data from a SQL server then output that data into a csv file for distribution.
The script is full operational but we would like to change the header names in the csv output file.
Here is an example:
$col1 = New-Object system.Data.DataColumn ProspectName,([string])
What we would want is the header row for this field to be 'Prospect Name'
Here is the complete script:
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0))
{
Write-Progress -Activity "Loading Modules" -Status "Loading Microsoft.SharePoint.PowerShell"
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")
$CuruntTime= Get-Date -format d
#All varaible
# Set the SharePoint Web Url.
$weburl = "http://newk-sharedev01:7763/bdforms/Marketing/"
#ConnectionString of NCOS Database.
$connString = "Server=testcrm1.rfs.com;DataBase=NCOS;Integrated Security=SSPI"
$TempLoc="C:\TempLocation\";
#Library Name where the weekly reports are stored.
$libraryname = 'WeeklyReport'
$succesfullUploadmessage="Weekly report uploaded successfully.";
$succesfulllsendmailmessage="Weekly report sent successfully to concern users."
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0))
{
Write-Progress -Activity "Loading Modules" -Status "Loading Microsoft.SharePoint.PowerShell"
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")
function Save-File([string] $Dir, [string] $PartialName, [system.Data.DataTable] $MyTable)
{
#writes file to the a temporary disk based location. I add a timestamp to name to ensure uniqueness. $PartialName is a text description used to start the filename
# export-csv does all the heavy lifting. Note the attribute "-NoTypeInformation" is needed so there isn't a header on top of the field headers
$timestamp = Get-Date
$timestampstr = $timestamp.Month.ToString("00") + "_" + $timestamp.Day.ToString() + "_" + $timestamp.Year.ToString("0000")
$PartialName='Weekly Report for'
$FileName = $Dir + '\' + $PartialName+'_'+$timestampstr+'.CSV';
$MyTable.rows | Export-Csv -Path $FileName -NoTypeInformation
return $FileName;
}
#writes file to the Reporting Library within SharePOint , adds timestamp to name to ensure uniqueness
function Upload-File([string] $FilePath)
{
# create the Variable destination and pass the URL of the SharePoint List
# Store the current user default credentials in the Variable Credentials
$credentials = [System.Net.CredentialCache]::DefaultCredentials;
# Create the object of the Webclient
$webclient = New-Object System.Net.WebClient;
# Pass the user credentials
$webclient.Credentials = $credentials; Get-ChildItem
# “For Each” loop will upload all of the files one by one onto the destination using the UploadFile method
Get-ChildItem $TempLoc | ForEach-Object { $webclient.UploadFile($weburl +"/" + $libraryname + “/” + $_.Name, “PUT”, $_.FullName)
Write-Host($succesfullUploadmessage);
$FileName=$_.FullName;
}
$ReportFilename = $weburl + "/" + $libraryname + "/" + $_.Name, "PUT", $_.FullName;
return $FileName ;
}
# If we are running in a Claims Authentication environment, we can strip off the claims tags
Function Strip-ClaimsHeader ($s)
{
if ($s.IndexOf('#') -gt 0) #handle stripping claims tags off name
{
return $s.Substring($s.IndexOf("#")+1)
}
else
{
return $s
}
}
Function Set-AlternatingRows {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[string]$Line,
[Parameter(Mandatory=$True)]
[string]$CSSEvenClass,
[Parameter(Mandatory=$True)]
[string]$CSSOddClass
)
Begin {
$ClassName = $CSSEvenClass
}
Process {
If ($Line.Contains("<tr>"))
{
$Line = $Line.Replace("<tr>","<tr class=""$ClassName"">")
$newstring= $Line.split("$");
#$newstring[1].Insert(0,'$')
$newstringl=$newstring[0].length;
$newstringlm=$newstringl - 1 ;
if($newstring[0].Contains("<th>"))
{
$Line = $Line.Replace("<th>ProspectName</th>","<th>Prospect Name</th>")
$Line = $Line.Replace("<th>IndustryPractice</th>","<th>Industry Practice</th>")
$Line = $Line.Replace("<th>ExpectedFees</th>","<th>Expected Fees</th>")
$Line = $Line.Replace("<th>LeadGenerator</th>","<th>Lead Generator</th>")
$Line = $Line.Replace("<th>LeadGenerator2</th>","<th>Lead Generator2</th>")
$Line = $Line.Replace("<th>SalesTeamCombined</th>","<th>SalesTeam Combined</th>")
$Line = $Line.Replace("<th>ServicesRequested</th>","<th>Services Requested</th>")
$Line = $Line.Replace("<th>ReferralPerson</th>","<th>Referral Person</th>")
$Line = $Line.Replace("<th>ReferralCompany</th>","<th>Referral Company</th>")
$Line = $Line.Replace("<th>ReferralType</th>","<th>Referral Type</th>")
$Line = $Line.Replace("<th>ServicingOffice</th>","<th>Servicing Office</th>")
}
if($newstring[0].Contains("<td>"))
{
$Line = $newstring[0].Insert($newstringlm," align=right") +'$' + $newstring[1]
}
if($Line.Contains("Total"))
{
$Line = $Line.Replace("<tr class=""$ClassName"">","<tr style='font-weight:bold' class=""$ClassName"">")
}
If ($ClassName -eq $CSSEvenClass)
{
$ClassName = $CSSOddClass
}
Else
{
$ClassName = $CSSEvenClass
}
}
Return $Line
}
}
#used for HTML processing and fixup; this is a bit dense, but it supports the PowerShell pipeline, and restores XML tags
Function Convert-HTMLEscape {
<#
convert < and > to < and >
It is assumed that these will be in pairs
#>
[cmdletbinding()]
Param (
[Parameter(Position=0,ValueFromPipeline=$True)]
[string[]]$Text
)
Process {
foreach ($item in $text) {
if ($item -match "<") {
<#
replace codes with actual symbols. This line is a shortcut to do two replacements
with one line of code. The code in the first set of parentheses revised text with "<". This
normally gets written to the pipeline. By wrapping it in parentheses it tells PowerShell to treat it
as an object so I can then call the Replace() method again and add the >.
#>
(($item.Replace("<","<")).Replace(">",">")).Replace(""",'"')
}
else {
#otherwise just write the line to the pipeline
$item
}
}
} #close process
} #close function
$env = "Prod" # I like setting flags for changing environment settings
if ($env -eq "Prod")
{
$spWeb = Get-SPWeb -Identity $weburl
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
}
$Subtable=New-Object system.Data.DataTable “Sub Table”
$table = New-Object system.Data.DataTable “WeeklyReport” #this is an internal name, that is not very important to set
$CSVtable= New-Object system.Data.DataTable “CSVWeeklyReport” #this is an internal name, that is not very important to set
$QueryText = "exec dbo.WeeklyReport"
$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = "EXEC dbo.sp_WeeklyReport"
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$SubSqlCommand = $SqlConnection.CreateCommand()
$SubSqlCommand.CommandText = "EXEC dbo.sp_SubTotalByOffice"
$SubDataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SubSqlCommand
$Subdataset = new-object System.Data.Dataset
$NumberofRecord=$DataAdapter.Fill($dataset)
$SubDataAdapter.Fill($Subdataset)
#SubTable
$Subcol1 = New-Object system.Data.DataColumn Offices,([string])
$Subcol2 = New-Object system.Data.DataColumn SubTotal,([string])
$Subtable.columns.add($Subcol1)
$Subtable.columns.add($Subcol2)
#Get Marketing User Email ID
$MarketingSqlCommand = $SqlConnection.CreateCommand()
$MarketingSqlCommand.CommandText = "EXEC dbo.sp_GetMarketingEmail"
$MarketingDataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $MarketingSqlCommand
$Marketingdataset = new-object System.Data.Dataset
$MarketingDataAdapter.Fill($Marketingdataset)
#Get Test Marketing User Email ID
$TestMarketingSqlCommand = $SqlConnection.CreateCommand()
$TestMarketingSqlCommand.CommandText = "EXEC dbo.sp_GetTestMarketingEmail"
$TestMarketingDataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $TestMarketingSqlCommand
$TestMarketingdataset = new-object System.Data.Dataset
$TestMarketingDataAdapter.Fill($TestMarketingdataset)
foreach ($thing in $Subdataset.Tables[0].Rows){
$row = $Subtable.NewRow()
$row.Offices = $thing["NC_Lead_Gen_Office"];
$row.SubTotal = "$" + $thing["SubTotal"];
$Total += $thing["SubTotal"];
$Subtable.Rows.Add($row)
}
$Subtable.Rows.Add("Total", "$" + $Total)
$RunStatus = "All the processing completed $(get-date)"
$Header = "Test Weekly Report"
$emailTitle = "Weekly Report email $($RunSummary)"
# this is a table style, collapsed, colored header.
$a = "<style>"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color:black;}"
$a = $a + "Table{background-color:#EFFFFF;border-collapse: collapse;}"
$a = $a + "TH{border-width:1px;padding:5px;border-style:solid;border-color:black;background-color:#DDDDDD;width:50px;}"
$a = $a + "TD{border-width:1px;padding-left:5px;padding-right:3px;border-style:solid;border-color:black;font-family: Arial; font-size: 10pt}"
$a = $a + ".odd{ background-color:#DCEDED; }"
$a = $a + ".even{ background-color:#D6DDDD; }"
$a =$a + "</style>"
$body= "Below is a list of new client opportunities generated this week. This system documents new assurance and tax opportunities for <b>new clients only</b>. If you have relationships or history with one of these organizations, please contact the OMP or lead generator immediately. The attached spreadsheet contains more details on these opportunities." -join '<BR>'
$br="<"
#Create a datatable
$table = New-Object system.Data.DataTable “Weekly Report” #this is an internal name, that is not very important to set
#let's define a field (column) for every possible field; even those we don't yet use in a given report
$col1 = New-Object system.Data.DataColumn ProspectName,([string])
$col2 = New-Object system.Data.DataColumn Industry,([string])
$col3 = New-Object system.Data.DataColumn IndustryPractice,([string])
$col4 = New-Object system.Data.DataColumn Contact,([string])
$col7 = New-Object system.Data.DataColumn ExpectedFees,([string])
$col8 = New-Object system.Data.DataColumn AnnualRevenue,([string])
$col9 = New-Object system.Data.DataColumn LeadGenerator,([string])
$col10= New-Object system.Data.DataColumn LeadGenerator2,([string])
$col11= New-Object system.Data.DataColumn LeadGeneratorOther,([string])
$col12= New-Object system.Data.DataColumn SalesTeamCombined,([string])
$col13= New-Object system.Data.DataColumn ServicesRequested,([string])
$col14= New-Object system.Data.DataColumn PublicCompany,([string])
$col15= New-Object system.Data.DataColumn PEStake,([string])
$col16= New-Object system.Data.DataColumn ProspectClinic,([string])
$col17= New-Object system.Data.DataColumn ReferralPerson,([string])
$col18= New-Object system.Data.DataColumn ReferralCompany,([string])
$col19= New-Object system.Data.DataColumn ReferralType,([string])
$col20= New-Object system.Data.DataColumn RefTypeDesc,([string])
$col21= New-Object system.Data.DataColumn ServicingOffice,([string])
$col22= New-Object system.Data.DataColumn Created,([string])
$col23= New-Object system.Data.DataColumn Modified,([string])
$col24= New-Object system.Data.DataColumn LeadDate,([string])
$col25= New-Object system.Data.DataColumn Office,([string])
# Just add the columns to the table
$table.columns.add($col25) # Office
$table.columns.add($col24) # Lead Date
$table.columns.add($col1) # Prospect Name
$table.columns.add($col2) # Industry
$table.columns.add($col3) # Industry Practice
$table.columns.add($col4) # Contact
$table.columns.add($col7) # Expected Fees
$table.columns.add($col8) # Annual Revenue
$table.columns.add($col9) # Lead Generator 1
$table.columns.add($col10) # Lead Generator 2
$table.columns.add($col11) # Lead Generator Other
$table.columns.add($col12) # Sales Team Combined
$table.columns.add($col13) # Services Requested
$table.columns.add($col14) # Public Company
$table.columns.add($col15) # PE Stake
$table.columns.add($col16) # Prospect Clinic
$table.columns.add($col17) # Referral Person
$table.columns.add($col18) # Referral Company
$table.columns.add($col19) # Referral Type
$table.columns.add($col20) # Ref Type Desc
$table.columns.add($col21) # Servicing Office
$table.columns.add($col22) # Date Created
$table.columns.add($col23) # Date Modified
if($dataset.Tables[0].Rows.Count -ne '0')
{
$FirstOffice=$dataset.Tables[0].Rows[0]["NC_Lead_Gen_Office"];
$LastOffices=$dataset.Tables[0].Rows[$NumberofRecord -1]["NC_Lead_Gen_Office"];
$ZTotal=0;
foreach ($thing in $dataset.Tables[0].Rows){
$row = $Table.NewRow()
if($FirstOffice -ne $thing["NC_Lead_Gen_Office"])
{
$table.Rows.Add( $FirstOffice + " Total","","","","","","{0:C2}" -f $ZTotal)
$FirstOffice =$thing["NC_Lead_Gen_Office"];
$ZTotal =0;
}
$row.Office = $thing["NC_Lead_Gen_Office"];
$row.LeadDate = $thing["NC_LeadDate"];
$row.ProspectName = $thing["NC_Prospect_Name"];
$row.Industry = $thing["nc_industry"];
$row.IndustryPractice = $thing["nc_industry_practice"];
$row.Contact = $thing["NC_Contact"];
$row.ExpectedFees = "{0:C2}" -f $thing["NC_Expected_Fees"];
$row.AnnualRevenue= $thing["NC_Annual_Revenue"];
$row.LeadGenerator = $thing["NC_Lead_Gen1"];
$row.LeadGenerator2 = $thing["NC_Lead_Gen2"];
$row.LeadGeneratorOther= $thing["NC_Lead_Gen_Other1"];
$row.SalesTeamCombined = $thing["NC_Sales_Combined"];
$row.ServicesRequested = $thing["NC_ServReq_Combined"];
$row.PublicCompany= $thing["NC_Public_Company"];
if($row.PublicCompany -eq 'True')
{
$row.PublicCompany='Yes';
}
else
{
$row.PublicCompany='No';
}
$row.PEStake = $thing["NC_PE_Stake"];
if($row.PEStake -eq 'True')
{
$row.PEStake='Yes';
}
else
{
$row.PEStake='No';
}
$row.ProspectClinic = $thing["NC_Prospect_Clinic"];
$row.ReferralPerson= $thing["NC_Referral_Person"];
$row.ReferralCompany = $thing["NC_Referral_Company"];
$row.ReferralType = $thing["NC_Referral_Type"];
$row.RefTypeDesc = $thing["NC_Referral_Note"];
$row.ServicingOffice = $thing["NC_Service_Office"];
$row.Created = $thing["NC_CreateDate"];
$row.Modified = $thing["NC_ModifyDate"];
$ZTotal += $thing["NC_Expected_Fees"];
if($LastOffices -eq $thing["NC_Lead_Gen_Office"])
{
$LTotal +=$thing["NC_Expected_Fees"];
}
$table.Rows.Add($row)
}
$LastSubTotal="{0:C2}" -f $LTotal;
$table.Rows.Add( $LastOffices + "Total","","","","","",$LastSubTotal)
foreach ($thing in $Subdataset.Tables[0].Rows){
$row = $table.NewRow()
$KTotal += $thing["SubTotal"];
}
$MainTotal= "{0:C2}" -f $KTotal
$table.Rows.Add("Total","","","","","","{0:C2}" -f $KTotal)
$MyOutput= $table |ConvertTo-Html Office,ProspectName,Industry,IndustryPractice,Contact,ExpectedFees,LeadGenerator,LeadGenerator2,SalesTeamCombined,ServicesRequested,PEStake,ReferralPerson,ReferralCompany,ReferralType,ServicingOffice -head $a -body "$body<br><br></br>" | Set-AlternatingRows -CSSEvenClass even -CSSOddClass odd | Convert-HTMLEscape
$f2 = save-file $TempLoc ($FileDescription) $table #Saves the temp file to disk, driven out of the $Table
# Get Value from NCOS Configuration list
$configurationList=$spWeb.Lists["NCOS Configuration"]
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$camlQuery = ‘<OrderBy><FieldRef Name="ID" /></OrderBy>'
$spQuery.Query = $camlQuery
$applicationMode
$SmtpServer
$SmtpUsername
$SmtpPassword
$SmtpPort
$from
$subject
$EnableSsl
do
{
$listItems = $configurationList.GetItems($spQuery)
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
{
if($item["Key"] -eq "ApplicationMode")
{
$applicationMode = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Host")
{
$SmtpServer = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Username")
{
$SmtpUsername = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Password")
{
$SmtpPassword = $item["Value"]
}
elseif($item["Key"] -eq "EmailFrom")
{
$from = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Port")
{
$SmtpPort = $item["Value"]
}
elseif($item["Key"] -eq "EnableSsl")
{
$EnableSsl = $item["Value"]
}
}
}
while ($spQuery.ListItemCollectionPosition -ne $null)
$Appmode = "Test"
$ReportURL = upload-file $f2
$FileName = $f2.Substring($f2.LastIndexOf("\")+1)
$ReportSummary = "";
$FullFileName=$TempLoc + $FileName;
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$att = new-object Net.Mail.Attachment($FullFileName)
$SmtpClient.host = $SmtpServer
#$SmtpClient.EnableSsl = true
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from = $from
#If application mode is "Test" then select the TEST Users otherwise Production Users
if($applicationMode.toLower() -ne $Appmode)
{
foreach ($thing in $Marketingdataset.Tables[0].Rows){
$ToRecipients +=$thing["NC_Email"] + ",";
$MailMessage.To.add($thing["NC_Email"])
}
$subject = "New Client Opportunities Generated Week of " + $CuruntTime
}
else
{
foreach ($thing in $TestMarketingdataset.Tables[0].Rows){
$ToRecipients +=$thing["NC_Email"] + ",";
$MailMessage.To.add($thing["NC_Email"])
}
$subject = "Testing New Client Opportunities Generated Week of " + $CuruntTime
}
Write-Host($ToRecipients);
$MailMessage.Subject = $subject
$MailMessage.Attachments.Add($att)
$MailMessage.Body = $MyOutput + "<br><p><font color='#943431'>Disclaimer :<br>Only viewable while inside the CohnReznick network.</font></p>" #"Body"
$MailMessage.set_IsBodyHtml($true)
#$smtp.EnableSSL = $false
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential($SmtpUsername, $SmtpPassword);
$SmtpClient.Send($MailMessage)
Write-Host($succesfulllsendmailmessage);
$att.Dispose();
$MailMessage.Dispose();
Remove-Item $FullFileName
}
else
{
# Get Value from NCOS Configuration list
$configurationList=$spWeb.Lists["NCOS Configuration"]
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$camlQuery = ‘<OrderBy><FieldRef Name="ID" /></OrderBy>'
$spQuery.Query = $camlQuery
$applicationMode
$SmtpServer
$SmtpUsername
$SmtpPassword
$SmtpPort
$from
$subject
$EnableSsl
do
{
$listItems = $configurationList.GetItems($spQuery)
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
foreach($item in $listItems)
{
if($item["Key"] -eq "ApplicationMode")
{
$applicationMode = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Host")
{
$SmtpServer = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Username")
{
$SmtpUsername = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Password")
{
$SmtpPassword = $item["Value"]
}
elseif($item["Key"] -eq "EmailFrom")
{
$from = $item["Value"]
}
elseif($item["Key"] -eq "Smtp.Port")
{
$SmtpPort = $item["Value"]
}
elseif($item["Key"] -eq "EnableSsl")
{
$EnableSsl = $item["Value"]
}
}
}
while ($spQuery.ListItemCollectionPosition -ne $null)
$Appmode = "Test"
$ReportSummary = "";
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$SmtpClient.host = $SmtpServer
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from = $from
if($applicationMode.toLower() -ne $Appmode)
{
foreach ($thing in $Marketingdataset.Tables[0].Rows)
{
$ToRecipients +=$thing["NC_Email"] + ",";
$MailMessage.To.add($thing["NC_Email"])
}
$subject = "New Client Opportunities Generated Week of " + $CuruntTime
}
else
{
foreach ($thing in $TestMarketingdataset.Tables[0].Rows){
$ToRecipients +=$thing["NC_Email"] + ",";
$MailMessage.To.add($thing["NC_Email"])
}
$subject = "Testing New Client Opportunities Generated Week of " + $CuruntTime
}
$MailMessage.Subject = $subject
$MailMessage.Body = "There is no data available to create New Client Opportunities weekly report. <br><p><font color='#943431'>Disclaimer :<br>Only viewable while inside the CohnReznick network.</font></p>"
$MailMessage.set_IsBodyHtml($true)
#$smtp.EnableSSL = $false
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential($SmtpUsername, $SmtpPassword);
$SmtpClient.Send($MailMessage)
Write-Host($succesfulllsendmailmessage);
$MailMessage.Dispose();
Write-Host "There is no data available to create weekly report.";
}