18 Reporting

_______________________________

In This Chapter

  • Screenshots
  • TXT Files
  • CSV Files
  • HTML Files
  • Delivery Methodologies
  • File Copy

_______________________________

When managing environments like Exchange Online, often the concentration of work to manage these is reviewing the configuration with Get cmdlets or making configuration changes with Set cmdlets. Of course there are other cmdlets starting with New, Remove, and so on. Either way the daily tasks such as adding mailboxes, changing settings in Exchange Online, looking for issues and scouring through Message Trace or Admin Audit logs will take up the majority of time and little time is given to documenting an environment or being proactive and producing daily reports. While documenting a Exchange Online certainly requires less effort due to there not being any servers to manage, reporting on Exchange Online's configuration is still important for the administrator.

PowerShell makes creating reports easy and while there are third party products that can produce canned results, they are not usually as flexible as PowerShell. With PowerShell, an administrator can choose the parameters to be reported on, the formatting and delivering method. Scripts can also be scheduled and contain error correction as needed depending on the intended results.

In this chapter, we will explore various reporting formats like TXT, CSV, HTML, and more. Delivery methods will also be explored and ways to schedule the reports. Real world scenarios will be used to help illustrate the usefulness of each method as well as the possibilities that each of these formats will provide.

Screenshots

The simplest method for using PowerShell to document an Exchange Online environment is to use screenshots to capture script results. The advantages to this method are that it is quick, simple and somewhat flexible. The disadvantages are that the results are harder to manipulate post screenshot and not as flexible for generating good documentation.

Using programs like the Windows Snipping Tool, OneNote, SnagIt and others can make quick snapshots of your PowerShell Script results. However, since this is a PowerShell book, I would only recommend using these tools as enhancements for documentation or reports that were created in PowerShell.

** Note ** It is important to note, that while screenshots can be helpful for referring to a proper configuration for something in Exchange Online, the screens and sections of the Exchange Online administration pages will change over time.

Let’s explore other options for creating documentation via PowerShell.

TXT Files

PowerShell provides a variety of ways to export results from cmdlets or scripts thus making results accessible for later review. One of these methods includes exporting any and all results to a text file.

Exporting the output can be done with a couple different methods. One is to use the ‘>’ symbol and specifying a TXT file name for output. The second method for exporting the results via the Out-File cmdlet. The below examples will explore both of these options for real world scenarios.

First, reporting the statistics for mailboxes in an Exchange Online environment requires a couple of cmdlets to gather the data. Get-Mailbox, which is piped to Get-MailboxStatistics to derive the numbers needed for an accurate report of all mailbox sizes. In addition to these cmdlets, some formatting has been inserted for attributes that are reported on. Note that Select-Object is being used to facilitate this:

Example – ‘>’

Get-Mailbox | Get-MailboxStatistics | Select-Object DisplayName,@{Expression={$_.TotalItemSize}; Label="Mailbox Size(MB)"} | ft -Auto > C:DownloadsMailboxStats.txt

** Note ** The '>' symbol can be used to create or overwrite an existing file, while using '>>' will append to an existing file.

This cmdlet drops the results of this cmdlet to a local text file:

Example – Out-File #1

Similar to the ‘>’ output symbol, the Out-File provides a method for exporting results of the cmdlet to a TXT file. However, Out-File provides more options for formatting the actual output; including Encoding, NoClobber, as well as width of the output.

Get-Mailbox | Get-MailboxStatistics | Select-Object DisplayName,@{Expression={$_.TotalItemSize}; Label="Mailbox Size(MB)"} | ft -Auto | Out-File -FilePath C:DownloadsMailboxStats-OF.txt -NoClobber

This PowerShell cmdlet drops the results to a local text file:

Notice that in terms of actual output or formatting, the text file is exactly the same for either ‘>’ or ‘Out-File’. The true differentiator will be the usage of NoClobber and Encoding. While Encoding was not used for this example, it is an available option. The NoClobber option is useful as it will prevent the overwriting a file by the output of this cmdlet. This is useful for running reports that may need to be reviewed later and having a script overwrite a file would make data analysis later impossible.

Example – Out-File # 2

The first example was a bit simple, based off a single cmdlet. In this example a script will be written to produce a report of licenses assigned to each user in Azure AD, then exported to a TXT file for reporting:

$Mailboxes = Get-MsolUser -All | Select-Object UserPrincipalName,Licenses

$Header1 = "Licensing for each mailbox:" | Out-File c:ReportsLicenses.txt -NoClobber

$Header2 = "---------------------------" | Out-File c:ReportsLicenses.txt -Append

Foreach ($Mailbox in $Mailboxes) {

$LicenseAll = $Null

$UPN = $Mailbox.UserPrincipalName

$ServicePlans = $Mailbox.Licenses.ServiceStatus

$Licenses = $Mailbox.Licenses

$SKUs = $Licenses.AccountSKUID

$LicenseCurrent = New-Object System.Object

$LicenseCurrent | Add-Member -Type NoteProperty -Name Mailbox -Value $UPN

Write-Host "$UPN" -ForegroundColor Cyan

Foreach ($Sku in $SKUs) {

If ($SKU -eq "OnlineExchangeBook:ENTERPRISEPACK") {

Foreach ($Line in $ServicePlans) {

$ServicePlan = $Line.ServicePlan.ServiceName

$ProvisioningStatus = $Line.ProvisioningStatus

$ServicePlan

$LicenseCurrent | Add-Member -Type NoteProperty -Name $ServicePlan -Value $ProvisioningStatus

}

$LicenseAll += $LicenseCurrent

}

$LicenseAll | Out-File c:ReportsLicenses.txt -Append

}

}

Contents of the resulting TXT file are:

Explanation of the Script

In the first part of the script, a header and underline are added for identification and documentation purposes. Note that the switch –append is not used on the first line. This is because the file needs to start fresh, with no content for the header, otherwise the ‘header’ would go to the bottom of the file and is then not a header.

The next section (inside the Foreach loop), a series of variables are set for the script user license query. The most complicate variable, $LicenseCurrent, is a system object because other information will be added to it a little later:

Next, we validate that the SKU is the correct one, which is TenantName:LicenseLevel. In this case that value would be 'OnelineExchangeBook:ENTERPRISEPACK':

This part of the script populates the $LicenseCurrent variable which is used to populate the results file like so:

From the script above and the previous Out-File and ‘>’ methodology, exporting the results of PowerShell can be used for reporting and can be formatted to your liking. The Out-File cmdlet is not a complex cmdlet and provides an easy way to create documentation or create a starting point for further reporting on an Exchange Server environment. The caveat is that it cannot be easily utilized for producing additional reports and these TXT reports are essentially just screen scrapes. The next section of this chapter, on CSV files, provides that next step of exporting data to a file that can be used for future reports and even as input to other systems or spreadsheets easily.

CSV Files

A CSV file can be constructed by using Export-CSV cmdlet in PowerShell. CSV files are a good data format for tables since their format can be used for future scripts. CSV file data is also similar in format to the format of an array of arrays used in PowerShell. They’re typically used as either a temporary data storage for a script for further processing, used by a different script or just to document values found in Exchange. In terms of documenting an Exchange messaging environment CSV files are useful for creating large data tables to be analyzed/reported on. They can also easily be imported into Excel and other tools for further data analysis and usage.

In terms of real world examples, CSV files can be used to document things such as:

  • Mailbox Statistics – name, number of items, database, server, mailbox size, quotas and more
  • Exchange Server Information – name, site, role, version, mailboxes on a server, etc.
  • Transport Settings – tracking logs, protocol logs and more
  • Mailbox Information – name, database, UPN, primary SMTP address, SIP Address and more
  • SMTP Connectors – server, connector name, connector type, Remote IPs, authentication and scoping

All of the examples above are good examples of what can be contained in these CSV files. How do we use PowerShell to create a CSV file? Let’s go through some practical examples of how to create files and use the data that is contained in the CSV file.

** Note ** The CSV delimiter value could be different depending on your region. Another sample delimiters is ';' which is used in German and Dutch language regions. Keep in mind that you can also specify a delimiter character if you wish.

Example 1

For this example, we have a project where IT Management has decided to upgrade Exchange 2016 to Exchange Online. In preparing for this project, as the Exchange administrator you need to gather a list of all mailboxes with the following data – Display Name, SAM Account Name, UPN, Primary SMTP Address and other values. This information will be stored as a CSV file for future work – UPN and/or Primary SMTP address corrections.

First, the main cmdlet for gathering information on Exchange Server mailboxes is ‘Get-Mailbox’. However, does this cmdlet provide all the criteria we are looking for on the mailboxes? Yes. Here is the cmdlet we need to cover all mailboxes:

Get-Mailbox | ft Name, UserPrincipalName, PrimarySMTPAddress, HiddenFromAddressListsEnabled, RetentionPolicy

** Note ** In most environments, the use of the -ResultSize Unlimited parameter should be used so that the number of results returned will not be capped at 1,000.

In a typical environment, this cmdlet will gather all user mailboxes in Exchange. At least one extraneous mailbox will show up in the report and it is the Discovery Mailbox. In order to eliminate this from the report we need to make an exception. The easiest way to make that exception is to use the filtering techniques used in Chapter 2.

Here is the filter to be used:

| Where {$_.Name -NotMatch "Discovery”}

This will exclude the Discovery Mailbox. The full one-liner is:

Get-Mailbox | Where {$_.Name -NotMatch "Discovery"} | ft Name, UserPrincipalName, PrimarySMTPAddress, HiddenFromAddressListsEnabled, RetentionPolicy

Before

After

Now that we have all the mailbox properties lined up, the data needs to be exported to a CSV file. What cmdlets are available for CSV export? What cmdlets have ‘CSV’ in them:

Get-Command *csv*

Export-Csv has several useful parameters for exporting the data from the above one-liner and export it to a usable CSV file:

Append

Delimiter

Encoding

Force

InputObject

NoClobber

NoTypeInformation

Path

UseCulture

LiteralPath

Example 2

In this example there is a need to monitor mailbox growth over time. In order to do so, the Get-MailboxStatistics cmdlet will be used in conjunction with the Export-CSV cmdlet to create CSV files every day which when combined together will then provide historical data. Each file will be tagged with a date (no time stamp) and the files created must not be overwritten. Using a similar process to Example 1 where the results of a cmdlet are exported to a CSV file. The additional criteria is that a different file be generated and placed in a shared folder:

$Date = Get-Date -Format "yyyy-MM-dd"

Get-Mailbox | Get-MailboxStatistics | Select-Object DisplayName,@{Expression={$_.TotalItemSize}; Label="Mailbox Size(MB)"}, ItemCount | Export-Csv $Date-MailboxStat.csv -NoClobber -NoType

This code is saved as a script and then scheduled to run once per day. The ‘NoClobber’ switch makes sure that none of the files are overwritten when the new daily file is generated. The ‘NoType’ switch makes sure that the format is clean for the CSV file.

Exporting the CSV file without using –NoType, results in the CSV file containing bad data (in the red rectangle):

Exporting the CSV file with the –NoType parameter removes this unneeded data:

Then the Get-Date cmdlet is stored in the $Date variable which is used to tag the file name. Key to that cmdlet is the formatting of the date to year-month-day (i.e. 2016-08-16).

To schedule PowerShell scripts, store the scripts in a secure location – isolated by NTFS permissions and placed on a share that is also locked down by permissions. Then the scheduled task will also need stored credentials to run.

The data is stored into a CSV file as such:

"DisplayName","Mailbox Size(MB)","ItemCount"

"Damian Scoles","1.377 MB (1,444,131 bytes)","409"

"John Doe","1.292 MB (1,354,656 bytes)","380"

"Dave Stork","4.584 MB (2,709,212 bytes)","980"

This data could now be used to create charts for trending data, in Excel for example. Imported one day of data into Excel, a data set would look like this:

HTML Files

When it comes to creating reports, HTML provides the most flexible platform for customization, creativity and informational overload. Visually speaking, HTML is excellent with the customization allowing for reports that are more visually presentable to the consumer of the report. This is important because the reports should be usable and read by the recipient of the report. Reports should be meaningful, containing real data that the recipient can readily understand and not ignore because it's just a table of numbers.

The most useful and information oriented HTML reports contain good coloring, column sizing, spacing and more. In this section on HTML reporting three types of reports will be covered:

  • Quick HTML Report
  • Some Formatting Present
  • Advanced Formatting

The first involves using just the Set-Content and ConvertTo-Html, basic, quick and easy. While the second involves some basic options for formatting using CSS and the ConvertTo-Html cmdlet. The last option is to use headers, table formatting and multiple sections of information put into an HTML file, using variables to assemble the content.

Quick HTML Reports

Get-Mailbox | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | ConvertTo-Html DisplayName,@{Expression={$_.TotalItemSize}; Label="Mailbox Size(MB)"}| Set-Content c: est.html

The previous one-liner does the following:

Code Section

What it does

Get-Mailbox

Finds all mailboxes in Exchange

| Get-MailboxStatistics

Pipes the mailboxes into the Get-MailboxStatistics cmdlet

| Sort-Object TotalItemSize -Descending

Sorts the Size (descending order)

ConvertTo-Html DisplayName, @{Label="TotalItemSize(MB)";Expression={$_.TotalItemSize.Value.ToMB()}}

Formats the table columns and values

| Set-Content c:ReportsTest.html

Exports content to an HTML file

As can be seen by the resulting HTML table, the results are really basic. For quick reports that need low effort, this report fits that need. HTML table can have as many fields as needed. Take for an example where a list of Retention Policy Tags in Exchange Online as part of documentation for the Exchange Online environment. A typical one-liner report allows for a formatted table of the results to be created:

Get-RetentionPolicyTag | ft Name,MessageClassDisplayName,RetentionEnabled,AgeLimitForRetention

Taking this same PowerShell one-liner and adding ConvertTo-Html, a portable document can be created and stored as part of an overall documentation of the Exchange Online Retention Policies:

Get-RetentionPolicyTag | ConvertTo-HTML Name, MessageClassDisplayName, RetentionEnabled, AgeLimitForRetention | Set-Content c:ReportsRetentionPolicyTags.html

Resulting HTML file:

Similar to the first HTML example, a portable HTML file is now available for IT to keep as a reference in case there are any issues. However, the formatting lacks quite a bit of finish – no header, no grid marking columns and rows.

Next, let’s add some polish to these HTML reports.

Adding Polish – Refining HTML Reports

Creating better HTML reports start with formatting and refining the look of the HTML output itself. This requires several features of HTML - CSS Styling, headers and possibly a footer as well. Each of these will provide value to the final file when it is delivered or printed out for documentation.

In this first example, the report generated will have a Header, Title and more added to it. At the very top of the HTML report will be this block of text. The colorful ‘rectangles’ refer back to the sections of code that made them possible:

Starting with the first line and ‘ConvertTo-Html’ portion of this one-liner, notice the following parameters that are being used:

  • Fragment - Defined because this section of code refers to only part of the HTML header being constructed
  • As Table - Formatting the output as a table
  • PreContent - Wording of this section of the HTML header

On the second line, starting with ‘ConvertTo-Html’ again, there are these parameters populated:

  • Title - The title as seen in a browser window
  • Head - Words to appear at the top of the spreadsheet

When coding the next part of the script, displayed in the next section, needs to include a CSS code section, for formatting the overall colors of the chart and other options. The value of the $CSS variable are stored between a pair of ' ' (single quotes). This example uses a black and white coloring scheme. <TD> sections are Black with White text and <TD> sections are White with Black text:

$Css='<style>table{margin:auto; width:98%};Body{background-color:Cyan; Text-align:Center;};th{background-color:black; color:white;};td{background-color:white; color:Black; Text-align:Center;};</style>'

The last line of the full code, which exists outside the configuration of the HTML file, is to actually export the HTML code to a text file:

$Report | Out-File $Filepath

Complete Coded Section

$FilePath = "c:Reports eport.html"

$Css='<style>table{margin:auto; width:98%};Body{background-color:Cyan; Text-align:Center;};th{background-color:black; color:white;};td{background-color:white; color:Black; Text-align:Center;};</style>'

$RetentionTags = Get-RetentionPolicyTag | Select-Object Name, MessageClassDisplayName, RetentionEnabled, AgeLimitForRetention

$RetentionTags| Export-CSV c:DownloadsInitialUserState-$date.csv -NoType

$RetentionTagsInfo= $RetentionTags| ConvertTo-Html -Fragment -As Table -PreContent "<h2>Current Retention Policy Documentation</h2>" | Out-String

$Report = ConvertTo-Html -Title "Current Retention Policy Tags" -Head "<h1>PowerShell Reporting</h1><br>This report was run on: $(Get-Date)" -Body "$RetentionTagsInfo $Css"

$Report | Out-File $FilePath

Sample results from this:

Detailed, Complex HTML Reporting

For the last section on HTML reporting, the creation of complex, detailed and visually appealing HTML files are what would have a wow factor or just considered more ‘accessible’ with color coding. This section will concentrate on creating a full HTML report with coloring, multiple charts, legends and more. For this scenario we’ll use a report of certain values for Exchange Server that should be configured a certain way. The report will contain the role, version, Operating System and more.

Caveats to this approach are that you must know HTML. Whole books have been written about HTML. Consider the next few pages a primer on how to combine HTML and PowerShell into one. Feel free to use snippets of code for your own scripts. This will make the script building process go quicker and allow one to explore the code to create more personalized reports.

First, a destination HTML file needs to be declared for holding the information to be gathered with PowerShell. To provide information on this code line, a comment will be included just above the file declaration line:

$HTMLReport = "c:ReportsBook-Retention-Policy-Tags.html"

Next we’ll need to begin building HTML files. This section starts with the variable which will store all information that will be exported to a HTML file:

$Output="<html><body>

Next, define the font for the header to be applied to the Header and the Subheader (if needed) – the two headers are defined with <h1> and <h3>:

<Font Size=""1"" face=""Calibri,Sans-Serif"">

<H1 Align=""Center"">Retention Policy Tags</H1>

<H3 Align=""Center"">Generated $((Get-Date).ToString())</H3>

</Font>

After the header has been created, a table is defined for the display of the data that will be gathered with PowerShell cmdlets – border is applied (“1”) and some room around each cell (“3”) is added. Also notice that there are double quotes around values, this is because it is being stored within a variable. This section is then closed off with a quote to end stop populating the $Output variable for now:

<Table Border=""1"" CellPadding=""3"" Style=""Font-Size:8pt;Font-Family:Arial,Sans-Serif"">

<tr bgcolor=""#3498db "">"

The HTML file now has a defined header with labels. After that, table headers need to be defined. Make sure there is one <th> per column (closed with ‘</th>’) and value that will be displayed. For this block four columns are defined for the four values. Two lines are used for readability, four lines could be used or even one long line could be used:

# Build Server Table Headers

$Output += "<th Colspan=""10000""><Font Color=""#ffffff"">Policy Tag</Font></th>"

$Output += "<th colspan=""10000""><Font Color=""#ffffff"">Message Class</Font></th>"

** Note ** this section is ended with ‘</tr>’ which will start a new section and a new line.

For the next section of the script, each Retention Policy Tag needs to have these values queries: Name, MessageClassDisplayName, RetentionEnabled and AgeLimitForRetention. First, it gathers the Tags information (stored in a variable called $RetentionPolicyTag) to process each tag in the Foreach loop:

$RetentionPolicyTag= Get-RetentionPolicyTag

# Build the Data Table

Foreach ($Tag in $RetentionPolicyTag) {

Here we set up all of the variables from the information provided by the current line ($Tag) in the $RetentionPolicyTag variable:

$Name = $Tag.Name

$MessageClassDisplayName = $Tag.MessageClassDisplayName

$RetentionEnabled = $Tag.RetentionEnabled

$AgeLimitForRetention = $Tag.AgeLimitForRetention

$Type = $Tag.Type

We use these values so that they can be placed into a column for the table. The column is started with ‘<td>’ and ended with ‘</td>’. In between this will be the variable value for each of the values defined above. Also defined are the width of the column (10000), the alignment of the text (center) and the font color (#000000). The variable also is defined as ‘$Output +=’ as this will append these lines to the $Output variable:

$Output += "<tr><td Colspan=""10000"" Align=""Center""><Font Color=""#000000"">$Name</Font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $MessageClassDisplayName</font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $RetentionEnabled </font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $AgeLimitForRetention</font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $Type</font></td></tr>"

At the end of the script, the $Output variable is closed up with "</body></html>" which closes off these sections in HTML.

# Ending the HTML FILE

$Output+="</body></html>"

Then the variable is exported to an HTML file:

# Export the Outlook variable to the HTML Report

$Output | Out-File $HTMLReport

The end result of the HTML script, looks like this:

Notice that some cells have a color assigned to them and that the table has defined columns. These column borders can be removed by changing its definition here - <table border=""0"">:

If for instance, an additional table needs to be added to this HTML file, simply add some lines like this:

$Output += “<BR><BR>”

Then add a new table the same way as the previous section.

Complete Script:

# HTML File name

$HTMLReport = "c:ReportsBook-Retention-Policy-Tags.html"

# Create the HTML Header for the report

$Output="<Html>

<Body>

<Font Size=""1"" face=""Calibri,Sans-Serif"">

<H1 Align=""Center"">Retention Policy Tags</H1>

<H3 Align=""Center"">Generated $((Get-Date).ToString())</h3>

</Font>

<Table Border=""1"" CellPadding=""3"" Style=""Font-Size:8pt;Font-Family:Arial,Sans-Serif"">

<tr Bgcolor=""#3498db "">"

# Build Server Table Headers

$Output += "<th Colspan=""10000""><Font Color=""#ffffff"">Policy Tag</Font></th>"

$Output += "<th colspan=""10000""><Font Color=""#ffffff"">Message Class</Font></th>"

$Output += "<th Colspan=""10000""><Font Color=""#ffffff"">Enabled</Font></th>"

$Output += "<th Colspan=""10000""><Font Color=""#ffffff"">Age Limit</Font></th>"

$Output += "<th Colspan=""10000""><Font Color=""#ffffff"">Type</Font></th></tr>"

# Build the Data Table

$RetentionPolicyTag= Get-RetentionPolicyTag

Foreach ($Tag in $RetentionPolicyTag) {

# Variables for table

$Name = $Tag.Name

$MessageClassDisplayName = $Tag.MessageClassDisplayName

$RetentionEnabled = $Tag.RetentionEnabled

$AgeLimitForRetention = $Tag.AgeLimitForRetention

$Type = $Tag.Type

# Lines for HTML table

$Output += "<tr><td Colspan=""10000"" Align=""Center""><Font Color=""#000000"">$Name</Font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $MessageClassDisplayName</font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $RetentionEnabled </font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $AgeLimitForRetention</font></td>"

$Output += "<td Colspan=""10000"" Align=""Center""><Font Color=""#000000""> $Type</font></td></tr>"

}

# Ending the HTML FILE

$Output+="</table></body></html>"

# Export the Outlook variable to the HTML Report

$Output | Out-File $HTMLReport

Delivery Methodologies

Once a report has been created and validated, a delivery method might need to be chosen. One of the most common delivery mechanism is email, but a file copy could also be employed. For this section on delivery we will go through both options to see how this can be done via PowerShell to deliver the report to their destination.

SMTP Delivery

Sending a report created in PowerShell via Exchange Online is probably the most common delivery method for PowerShell reporting. Email delivery requires a few things:

  • IP Address or FQDN of the Exchange Server to relay email through
  • The location of the source document to be sent
  • Determine if the file is to be attached or inserted into the body of an email
  • The destination email address
  • The sender email address
  • Subject line of the email messages

Each of these parameters will fit into a variable to be defined and then placed into the section of code that handles the email sending. First, how do we send an email in PowerShell? Well, let’s search for the cmdlet:

Get-Command *Message

There is a cmdlet called Send-MailMessage, which looks appropriate for our task at hand. Reviewing the parameters of the cmdlet using ‘Get-Help Send-MailMessage –full’ and we find these parameters are needed:

-Attachments The location of the source document to be sent

-Body Determine if the file is to be attached or inserted into the body of an email

-BodyAsHtml Would be used if sending the report in the body of the email

-From The sender email address

-SmtpServer IP Address or FQDN of the Exchange EXO to relay email through

-Subject Subject line of the email messages.

-To The destination email address

Now that the parameters are known, variables can be defined and placed into the cmdlet to send the email:

$Body = "Forgot about today's meeting."

$From = "[email protected]"

$To = “[email protected]

$SMTPServer = "smtp.office365.com"

$Subject = “Test”

$Attachment = "C:ReportsTest.Html"

** Note ** The server smtp.office365.com is Microsoft's defined connection point for SMTP traffic.

Incorporating all the variables above and using them for the Send-MailMessage cmdlet, the cmdlet looks like this:

$Credential = Get-Credential

Send-MailMessage -From $From -to $To -subject $Subject -body $Body -priority High -SmtpServer $SMTPServer -Credential $Credential -UseSsl -Port "587"

Make sure to include the 'Credential' parameter as the message will fail to send:

We can also add an attachment using the '-Attachment' parameter and specifying a file to send to the recipient who can then open it up from their mail client:

$Credential = Get-Credential

Send-MailMessage -From $From -to $To -subject $Subject -body $Body -priority High -SmtpServer $SMTPServer -Credential $Credential -UseSsl -Port "587" -Attachment $Attachment

If, however, the report needed to be in the body of the message, the script would be changed as follows:

$Body = Get-Content "\laptop.domain.comc$downloads est.html" –Raw

Send-MailMessage -To $To -From $From -Subject $Subject -Attachment $Attachment -Body $Body -BodyAsHTML -SmtpServer $SMTPServer -Credential $Credential -UseSsl -Port "587"

We included the -Attachment also, in addition to replacing the body with the same HTML code. The $body variable stores the HTML file since it the message body will be the HTML file and the -RAW switch will help facilitate that. The email arrives in the destination mailbox as so, with the HTML document pasted into the body of the message.

File Copy

Copying reports to a central location can be a solid alternative to sending all reports through email. By doing so, these files are accessible and possibly kept indefinitely for historical reporting. What cmdlets can be used for moving files to file servers? The BITS Transfer service would be ideal for moving files. What cmdlets are available for this service?

Get-Help *BITS*

Reviewing the list above, what cmdlets from this list are needed for transferring files from place to place? Start-BitsTransfer will copy a file from a source to a destination. This cmdlet is similar to a file copy daemon on steroids. Start-BitsTransfer has quite a few options to choose for running the cmdlet:

Depending on the destination and how a file needs to be transferred, BITS could be the ideal solution. It is useful if a large number of large files need to be transferred as BITS will dynamically associate bandwidth with a file transfer, run in the background and handle transfers even with network interruptions. In Chapter 3, this cmdlet is used in the script built to download files for use on servers. In the case of documentation, the cmdlets can now be used to move these documentation files to a central location.

In order to copy files to a central location, there is a need to define the source files that need to be moved, where the files will be moved to and if any sort of logging, authentication or priority needs to be assigned to these jobs. Retry intervals can be configured if the files are pulled from a source over a slow or notoriously high latency connection and to adjust for these connections ‘RetryInterval’ and/or ‘RetryTimeout’.

Example

For this example the requirement for the script is to pull locally run results files like CSV, HTML and or text files from five different global locations. These results will deposited on one server and stored for analysis by the global IT team located in the US global headquarters. Locations and destinations are known, for three of the five links are to overseas locations are low latency. Two other links are high latency and need to be accounted for. Let’s begin by focusing on the low latency links and work our way out to the high latency link. The jobs should log and if possible the transfer jobs should be described accurately. No special authentication is needed.

Low Latency

For the low latency links, the source and destination options are a given and are filled with the source and destination files. The priority is defined in case this needs adjustments later. To help identify the BITS Transfer, a description and name are given to the processes transferring files. Here are the three BITS Transfer PowerShell one-liners for this process:

Start-BITSTransfer –Displayname “Exchange HTML From GB” –Description “Exchange Information – British Servers” -Priority Normal -Source \GB-FILE01Reporting*.html –Destination \US-SRV-FS01ReportingExchange

Start-BITSTransfer –Displayname “Exchange HTML From Poland” –Description “Exchange Information – Polish Servers” -Priority Normal -Source \POL-FILE01Reporting*.html –Destination \US-SRV-FS01 ReportingExchange

Start-BITSTransfer –Displayname “Exchange HTML From Canada” –Description “Exchange Information – Canadian Servers” -Priority Normal -Source \CAN-FILE01Reporting*.html –Destination \US-SRV-FS01ReportingExchange

With the above cmdlets, all files are being copied to the same root folder and not a specific folder for each server. It is assumed that all files are unique and identifiable from the location that they come from. For example each set of files could be prefaced with a location and then the current date. This helps identity where and when these files are generated.

High Latency

For higher latency links, the same criteria above is used, with the addition of higher Retry Internal and Timeout. This is done because of the higher latency of the links. These values would be tweaked over time to adjust for any issues on these links.

Start-BITSTransfer –Displayname “Exchange HTML From China” –Description “Exchange Information – Chinese Servers” -Priority High -RetryInterval 900 -RetryTimeout 2419200 -Source \CH-FILE01Reporting*.html –Destination \US-SRV-FS01ReportingExchange

Start-BITSTransfer –Displayname “Exchange HTML From SA” –Description “Exchange Information – South African Servers” -Priority High -RetryInterval 900 -RetryTimeout 2419200 -Source \SA-FILE01Reporting*.html –Destination \US-SRV-FS01ReportingExchange

In summary, the BITS Transfer process can be used to move files between destinations with some advantages over a regular file copy. BITS transfer jobs that error or timeout can be examined with the Get-BITSTransfer cmdlet. There are policies that could be applied if necessary to manipulate the file transfer as well. For large file transfers the BITS Transfer can be monitored and manipulated while in flight (Set-BITSTransfer) and Get-BITSTransfer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243