In terms of “Best practices”, here’s what I would do differently:
- Don’t set $ErrorActionPreference to “SilentlyContinue”. Sweeping errors under the rug and not handling them is a bad habit. You don’t have to handle them with code, but the person running the script should at least see them.
- Write-Output probably isn’t the right choice for those lines. Write-Output sends objects down the pipeline; it’s a way for functions or scripts to produce that sort of output. When you want to write text to the screen (for status updates, etc), but NOT send extra string objects down the pipeline, you can choose from Write-Host, Write-Verbose, or Write-Progress, depending on what type of visibility and functionality you want.
- As Art mentioned, try to avoid backticks as the line continuation character wherever possible. It’s a hard character to see in some fonts, and if you put any spaces after the backtick, you get errors.
- Your use of spaces around operators is a bit inconsistent. $Servers = (gc “\\uncpath\to\servers.txt”) is easier to read than $Sender=”ServerDiskReport@company.com” , for example, and $PercentFree=@{name=”PercentFree(%)”;Expression={[int](($_.FreeSpace/$_.Size)*100)}} is really a headache to read. Try to write code that is clear and easy to read; add spaces or blank lines wherever they seem to enhance that quality.
Other than that, it’s minor stuff. Some people will say you should use single-quoted strings anytime you don’t intend to perform variable expansion or embed special characters like “`r`n”. That’s personal preference, so long as you’re aware of the differences between single and double quoted strings, and use them both correctly.
When you’re setting up your $html string at the beginning of the script, you could just use a multi-line string or here-string, rather than doing all the concatenation. With a short string, you won’t notice the performance difference, but doing operations like $string += “Some new text” can get very expensive as the string gets long.
Here’s an example of what it might look like using a here-string. Check out Get-Help about_Quoting_Rules for more details on here-strings; it also has the skinny on single quotes versus double quotes.
$html = @" <style> BODY{background-color:White;} TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;} TH{border-width: 1px;padding: 0px;border-style: solid;border-color: LightGrey;background-color:#F0E68C} TD{border-width: 1px;padding: 0px;border-style: solid;border-color: LightGrey;background-color:#FAFAD2} </style> "@
All of that stuff aside, the code looks like it works, which is mostly what counts at the end of the day. Nice job!