问题
I have a backup script WSBREPORT which works fine. However, I am using an SMTP server that needs authentication. So I have a script separately that works and creates an encrypted txt file with the password.
What I can't seem to achieve is to add the authentication script into my backup script.
Could you point me into the direction where my script needs to go to get it working, please.
************Working authentication Script ***********
$AdminName = "username"
$Pass = Get-Content "C:\Masters\WIN SERVER BACKUP SCRIPT\cred.txt" | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
Send-MailMessage –From alerts@co.uk –To backups@co.uk –Subject “ WSB Report” –Body “The backup report is attached” -SmtpServer smtp.office365.com -Credential $cred -UseSsl -Port 587
************ Working REPORT SCRIPT ******************
<#
.SYNOPSIS
This script creates a Windows Server Backup report that is easy to understand at a glance.
.DESCRIPTION
Usage: It can be used without parameters, just make sure to fill in the default variables below.
Usage: WSBREPORT.ps1 [-CompanyName <string>] [-smtpServer <string>] [-FromAddress <string>] [-ToAddress <string>] [-SendEmail <boolean>]
.PARAMETER $CompanyName
This is the company name of your client's business.
.PARAMETER $smtpServer
Your SMTP server address.
.PARAMETER $FromAddress
Email address which will send the backup result.
.PARAMETER $ToAddress
List of emails addresses which will receive the backup result separated by commas.
.PARAMETER SendEmail
Send email? TRUE : FALSE
.EXAMPLE
.NOTES
Compatible with Windows Server 2008 and above. PowerShell 2.0 and above.
Administrator Privileges Required.
#>
###########################################################################################################################################
###########################################################################################################################################
# Command line augments are supported. Change the default settings when ran with NO command line augments.
$Pass = Get-Content "C:\Masters\WIN SERVER BACKUP SCRIPT\cred.txt" | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
Param(
[string]$CompanyName = "Company Name", # The name of the company.
[string]$smtpServer = "outlook.office365.com", # The SMTP Server address. Obtainable form your ISP or Exchange server.
[string]$FromAddress = "alerts@co.uk", # The From Email address.
[string]$ToAddress = "backups@co.uk", # The TO addresses Separated by a Comma.
[bool]$SendEmail = $True # ($TRUE | $FALSE) Send email.
)
[bool]$ShowReport = $False # ($TRUE | $FALSE) Show the report in your default web browser. (Used for testing. Set this to FALSE in your production environment.)
# Set your warning and critical thresholds for disk space.
[int]$percentWarning = 15
[int]$percentCritcal = 10
# TIP: If free space drops below 15 percent, you will see that Windows will start to delete ShadowCopies to maximize free space.
[bool]$CleanOldReports = $TRUE; # ($TRUE | $FALSE Delete the old local reports. (Will only delete .html files)
[int]$CleanUpDays = 14 # Search .LOG files and delete then after X days.
[string]$OutPutPath = "C:\Scripts\WSBREPORT\Windows_Server_Backup_Reports" # This is the path for the html report.
# Report Color Theme. HEX values
[string]$ResultGoodColor = "#86aa65"
[string]$ResultGoodColor1 = "#444e3d"
[string]$ResultWarnColor = "#5d4d30"
[string]$ResultWarnColor1 = "#eda637"
[string]$ResultBadColor = "#db4d4c"
[string]$ResultBadColor1 = "#583534"
[string]$PageBGColor = "#2f2f2f"
[string]$TableBGColor = "#2f2f2f"
[string]$CellBGColor = "#323232"
[string]$BorderColor = "#686767"
[string]$TextColor = "#F5F5FF"
[string]$TextBodyColor = "#F5F5FF"
[string]$TableHeadingColor = "#21536B"
[string]$TextTitleColor = "#F5F5FF"
# No need to change things below here.
###########################################################################################################################################
###########################################################################################################################################
[string]$ReportColor = $ResultGoodColor1
# This function will attempt to elevate the privileges to an Administrator level then re-run the script. Else exit.
# TIP: If this function does nothing and you have permissions, check your "get-executionpolicy" settings in an elevated PowerShell instance.
FUNCTION ElevateThis {
# Check if script is running as Administrator and if not use RunAs.
# Use Check Switch to check if Admin
param([SWITCH]$Check)
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
IF ($Check) { RETURN $IsAdmin }
IF ($MyInvocation.ScriptName -ne "") {
IF (-not $IsAdmin) {
try {
$arg = "-file `"$($MyInvocation.ScriptName)`""
Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'
}
catch {
Write-Host "Error - Failed to elevate the script. Please run the script as Administrator."
BREAK
}
exit # Quit this session.
}
}
ELSE {
Write-Host "Error - Script must be saved as a .ps1 file first"
BREAK
}
}
# Check for Admin permissions.
Write-Host "Checking For Administrator Credentials..." -ForegroundColor yellow
IF ([bool]((whoami /all) -match "S-1-16-12288")) {Write-Host "This Script Has Administrator Permissions" -ForegroundColor Green} ELSE { Write-host "No Administrator Permissions. Trying To Elevate..." -ForegroundColor Red }
Start-Sleep 1 # Give it a second to process before continuing.
ElevateThis # Try to elevate the permissions.
# Register the Windows Server Backup CMDLET. If this errors, then likely no WBAdmin role installed.
IF ( $null -eq (Get-PSSnapin -Name Windows.ServerBackup -ErrorAction SilentlyContinue) ) {Add-PsSnapin Windows.ServerBackup -ErrorAction SilentlyContinue}
# Check if SharePoint needs a manual upgrade.
$SPConfig = "<font color=""$ResultGoodColor"">FALSE</font>"
IF (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) {
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
IF ((get-spserver $env:computername).NeedsUpgrade -eq $True)
{$SPConfig = "<font color=""$ResultBadColor"">TRUE</font>" }
}
# Get the machine up time.
Function GetUpTime {
param([string] $LastBootTime)
$Uptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($LastBootTime)
"$($Uptime.Days) Days; $($Uptime.Hours) Hours; $($Uptime.Minutes) Minutes"
}
function Get-External-IP {
# Website URL in a variable, This should simply return the IP address in plain text.
$IPurl = "https://ipinfo.io/ip"
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create($IPurl)
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
# Close the HTTP request.
$HTTP_Response.Close()
# If Error code 200, all is good. If any other error code like 404, page page not found.
If ($HTTP_Status -eq 200) {
$webclient = New-Object System.Net.WebClient
$ExternalIPAddress = $webclient.DownloadString($IPurl)
}
Else {
$ExternalIPAddress = "Unknown"
}
RETURN $ExternalIPAddress
}
Function FormatBytes {
Param
(
[System.Int64]$Bytes
)
[string]$BigBytes = ""
#Convert to TB
If ($Bytes -ge 1TB) {$BigBytes = [math]::round($Bytes / 1TB, 2); $BigBytes += " TB"}
#Convert to GB
ElseIf ($Bytes -ge 1GB) {$BigBytes = [math]::round($Bytes / 1GB, 2); $BigBytes += " GB"}
#Convert to MB
ElseIf ($Bytes -ge 1MB) {$BigBytes = [math]::round($Bytes / 1MB, 2); $BigBytes += " MB"}
#Convert to KB
ElseIf ($Bytes -ge 1KB) {$BigBytes = [math]::round($Bytes / 1KB, 2); $BigBytes += " KB"}
#If smaller than 1KB, leave at bytes.
Else {$BigBytes = $Bytes; $BigBytes += " Bytes"}
Return $BigBytes
}
Function BackupItems {
Param
(
[System.String]$Name,
[System.String]$Type,
[System.String]$Status,
[System.Int64]$BytesProcessed,
[System.Int64]$TotalBytes
)
$Item = New-Object System.Object;
$Item | Add-Member -Type NoteProperty -Name "Name" -Value $Name;
$Item | Add-Member -Type NoteProperty -Name "Type" -Value $Type;
$Item | Add-Member -Type NoteProperty -Name "Status" -Value $Status;
$Item | Add-Member -Type NoteProperty -Name "Size" -Value ((FormatBytes -Bytes $BytesProcessed) + " of " + (FormatBytes -Bytes $TotalBytes));
Return $Item;
}
# Generate the report.
FUNCTION GenerateTheReport {
Write-host "Generating Backup Report..." -ForegroundColor yellow
try {
$WBSummary = Get-WBSummary
[string]$WBLastSuccess = ($WBSummary.LastSuccessfulBackupTime).ToString("yyyy-MM-dd HH:mm")
[string]$WBResult = $WBSummary.LastBackupResultHR
[string]$WBErrorMsg = $WBSummary.DetailedMessage
[string]$WBTarget = $WBSummary.LastBackupTarget
[string]$WBLable = $WBSummary.LastSuccessfulBackupTargetLabel
[string]$WBNoOfVersions = $WBSummary.NumberOfVersions
[string]$WBNextSchedule = ($WBSummary.NextBackupTime).ToString("yyyy-MM-dd HH:mm")
$WBJob = Get-WBJob -Previous 1
[string]$WBStartTime = $WBJob.StartTime
[string]$WBEndTime = $WBJob.EndTime
[string]$WBDuration = (New-TimeSpan -Start $WBJob.StartTime -End $WBJob.EndTime)
$BackupItemResults = @()
$WBJob | ForEach-Object {
$_.JobItems | ForEach-Object {
$BackupItem = $null
If ($_.Name -eq 'VolumeList') {
$_ | ForEach-Object {$_.SubItemList | ForEach-Object {
$BackupItem = BackupItems -Name $_.Name -Type $_.Type -Status $_.State -BytesProcessed $_.BytesProcessed -TotalBytes $_.TotalBytes
$BackupItemResults += $BackupItem
}
}
}
Else {
$_ | ForEach-Object {
$BackupItem = BackupItems -Name $_.Name -Type $_.Type -Status $_.State -TotalBytes $_.TotalBytes
$BackupItemResults += $BackupItem
}
}
}
}
$BackupItemHTML = $BackupItemResults | ConvertTo-HTML -Fragment
$xml = [xml]$BackupItemHTML
$attr = $xml.CreateAttribute('id')
$attr.Value = 'items'
$xml.table.Attributes.Append($attr) | out-null
$BackupItemHTML = $xml.OuterXml | out-string
$BackupItemHTML = ($BackupItemHTML -replace "<td>Completed</td>", "<td style=""background-color:$ResultGoodColor1;""><font color=""$ResultGoodColor""> Completed Successfully </td>")
$BackupItemHTML = ($BackupItemHTML -replace "<th>Size</th>", "<th>Data Transferred</th>")
}
catch {$WBErrorMsg = "Windows Server Backup Role Is Not Installed."}
IF ($WBResult -eq 0) {
# The Windows Server Backup has completed successfully.
$ReportColor = "$ResultGoodColor1"
$WBResult = "This backup has completed <font color=""$ResultGoodColor""><B>Successfully!</B></font><BR>"
}
ELSE {
# The Windows Server Backup has failed!
$ReportColor = "$ResultBadColor1"
$WBResult = "This backup has <font color=""$ResultBadColor""><B>Failed!</B></font><BR>"
}
# Place the backup status into the subject line of the email report.
IF ($WBSummary.LastBackupResultHR -eq 0) {$ReportSubject = "$Windows Server Backup Result: Passed"}
ELSE {$ReportSubject = "$Windows Server Backup Result: Failed"}
# Get the current time.
$CurrentTime = (Get-Date -format "yyyy-MM-dd HH:mm");
# Get the PowerShell version of the running instance.
$VarPsVersion = $PSVersionTable.PSVersion
# Get the machine name for latter use.
$TheMachineName = (Get-Item env:\Computername).Value
# Get the operating system name.
$OperatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $TheMachineName -ErrorAction SilentlyContinue
# Get the Operating System Name
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $TheMachineName
# Get the up time of the machine.
$Uptime = GetUptime( $OperatingSystem.LastBootUpTime )
# Get the local IP address.
$LocalIP = (Get-WmiObject -class win32_NetworkAdapterConfiguration -FILTER 'ipenabled = "true"').ipaddress[0]
# Get the local MAC address.
$nwMacADD = ((Get-WmiObject -ComputerName $TheMachineName Win32_NetworkAdapterConfiguration | Where-Object { $null -ne $_.IPAddress }).MACAddress -split " ")[0] + ' '
# Get the external IP address.
$myExternalIP = Get-External-IP
# Check if the machine is a virtual or physical machine. $ MachineHardwareType will be the value for the report.
$compsys = get-wmiobject -computer $TheMachineName win32_computersystem
try {IF ((Test-Path "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters") -eq $TRUE) {$VMHostName = (get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters").GetValue("HostName")}}catch {write-host "Cannot find VMHost name."}
IF ($compsys.model.toupper().contains("VIRTUAL")) {$MachineHardwareType = "Virtual Machine; Guest of: $VMHostName"}ELSE {$MachineHardwareType = "Physical Machine"}
# Look for corrupted/temporary user profiles.
$ProfileBak = "<font color=""$ResultGoodColor"">FALSE</font>"
IF (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*" | Where-Object PSPath -Like "*.bak")
{$ProfileBak = "<font color=""$ResultBadColor"">TRUE</font>"}
$tableHeader = "
<table class=""hdd"">
<TR>
<TH width='20%'><B>Label:</B></TH>
<TH width='30%'><B>Volume:</B></TH>
<TH width='10%'><B>Total Capacity:</B></TH>
<TH width='10%'><B>Used Space:</B></TH>
<TH width='10%'><B>Free Space:</B></TH>
<TH width='15%'><B>Percent Free:</B></TH>
<TH width='10%'><B>Dirty:</B></TH>
</TR>
"
$StorageInfo = $tableHeader
$disks = Get-WmiObject -ComputerName $TheMachineName -Class Win32_Volume | Where-Object {$_.Label -ne "System Reserved"}
FOREACH ($disk IN $disks) {
$VolumeLabel = $disk.Label
$volName = $disk.Name
# Check if the volume is marked as Dirty.
[string]$volDirty = $disk.DirtyBitSet
$DirtyBitText = $ResultGoodColor;
$DirtyBitColor = $ResultGoodColor1;
IF ($volDirty -eq "True") {
$DirtyBitText = $ResultBadColor;
$DirtyBitColor = $ResultBadColor1;
}
[float]$size = $disk.Capacity
[float]$freespace = $disk.FreeSpace
[string]$percentFree = [Math]::Round(($freespace / $size) * 100, 2)
$sizeGB = [Math]::Round($size / 1073741824, 1)
$freeSpaceGB = [Math]::Round($freespace / 1073741824, 1)
$usedSpaceGB = [Math]::Round($sizeGB - $freeSpaceGB, 1)
# Set background color to Green if it's a Good result. So far.
$DiskText = $ResultGoodColor;
$DiskColor = $ResultGoodColor1;
# Set background color to Orange if it's a Warning result. So far.
IF ($percentFree -lt $percentWarning) {$DiskText = $ResultWarnColor1}
IF ($percentFree -lt $percentWarning) {$DiskColor = $ResultWarnColor}
# Set background color to Orange if it's a Critical result. So far.
IF ($percentFree -lt $percentCritcal) {$DiskText = $ResultBadColor}
IF ($percentFree -lt $percentCritcal) {$DiskColor = $ResultBadColor1}
IF ($percentFree.contains("a")) {$percentFree = ""}ELSE {$percentFree = $percentFree + "%"}
$dataRow = "
<tr>
<td>$VolumeLabel</td>
<td>$volName</td>
<td>$sizeGB GB</td>
<td>$usedSpaceGB GB</td>
<td>$freeSpaceGB GB</td>
<td style=""background-color:$DiskColor;""><font color=""$DiskText""><B>$percentFree</td>
<td style=""background-color:$DirtyBitColor;""><font color=""$DirtyBitText""><B>$volDirty</td>
</tr>
"
$StorageInfo = $StorageInfo + $dataRow
}
# Get the Volume Shadow Copy Writers using the command 'vssadmin list writers' then filter them into our html results.
$VSSListResults = VSSADMIN LIST WRITERS
FOREACH ($result IN $VSSListResults) {
$nextline = ""
IF ($result.contains("Writer name:")) {$nextline = $nextline + "`n" + "<tr><td>" + $result.split(":")[1] + "</td>"}
IF ($result.contains("State:")) {
IF (($result.split(":")[1]).contains("[1]")) {$nextline = $nextline + "<td style=""background-color:$ResultGoodColor1;""><font color=""$ResultGoodColor"">" + $result.split(":")[1] + "</font></td>"}
ELSEIF (($result.split(":")[1]).contains("[5]")) {$nextline = $nextline + "<td style=""background-color:$ResultWarnColor;""><font color=""$ResultWarnColor1"">" + $result.split(":")[1] + "</font></td>"}
ELSEIF (!($result.split(":")[1]).contains("[1]")) {$nextline = $nextline + "<td style=""background-color:$ResultBadColor1;""><font color=""$ResultBadColor"">" + $result.split(":")[1] + "</font></td>"}
}
IF ($result.contains("Last error:")) {
IF (!($result.split(":")[1]).contains("No error")) {$nextline = $nextline + "<td style=""background-color:$ResultBadColor1;""><font color=""$ResultBadColor"">" + $result.split(":")[1] + "</font></td></tr>"}
ELSEIF (($result.split(":")[1]).contains("No error")) {$nextline = $nextline + "<td style=""background-color:$ResultGoodColor1;""><font color=""$ResultGoodColor"">" + $result.split(":")[1] + "</font></td></tr>"}
}
IF (!($nextline.contains("[1] Stable, No error"))) {$VSSResults = $VSSResults + $nextline}
}
$VSSResults = "<table class=""VSSTable"" style=""width:100%""<tr><th><B>Writer name:</B></th><th><B>State:</B></th><th><B>Last error:</B></th></tr>" + $VSSResults + "</table>"
# Compile all of our results into html code.
$sb = New-Object System.Text.StringBuilder ""; # We use StringBuilder to create the HTML document and store it in $sb for later use.
$sb.AppendLine( "
<!DOCTYPE html>
<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
<head>
<title>Windows Server Report</title>
<style type=""text/css"">
body {color:$TextColor; font-family:Verdana; background:$PageBGColor;}
.VSSTable {table-layout: fixed; font-size:12px; color:$TextColor; width:100%; border-width:0px; border-color:$BorderColor; border-collapse:collapse;}
.VSSTable th {color:$TextTitleColor; font-size:13px; background-color:$TableHeadingColor; border-width:1px; padding:8px; border-style:solid; border-color:$BorderColor; text-align:center;}
.VSSTable tr {color:$TextBodyColor; font-size:13px; background-color:$PageBGColor;}
.VSSTable td {border-width:1px; padding:5px; border-style:solid; border-color:$BorderColor; background-color:$TableBGColor}
.hdd {table-layout:fixed; font-size:12px; color:$TextColor; width:100%; border-width:px; border-color:$BorderColor; border-collapse:collapse;}
.hdd TH {color:$TextTitleColor; font-size:13px; background-color:$TableHeadingColor; border-width:1px; padding:8px; border-style:solid; border-color:$BorderColor; text-align:center;}
.hdd TR {color:$TextBodyColor; font-size:13px; background-color:$PageBGColor;}
.hdd TD {border-width:1px; padding:5px; border-style:solid; border-color:$BorderColor; background-color:$TableBGColor; text-align:center;}
.docHeader h1 {color:$TextColor; font-size:120%; text-align:center; background:$ReportColor;}
.docHeader h3 {color:$TextColor; font-size:110%; text-align:center; background:$ReportColor;}
.docHeader style=""width:100%""
.BackupItem {table-layout: fixed; font-size:12px; color:$TextColor; width:100%; border-width:1px; border-color:$BorderColor; border-collapse:collapse;}
.BackupItem th {color:$TextTitleColor; font-size:13px; background-color:$TableHeadingColor; border-width:1px; padding:8px; border-style:solid; border-color:$BorderColor; text-align:center;}
.BackupItem tr {color:$TextBodyColor; font-size:13px; background-color:$PageBGColor;}
.BackupItem td {border-width:1px; padding:5px; border-style:solid; border-color:$BorderColor; background-color:$TableBGColor}
</style>
</head>
<body>
<table class=""docHeader"">
<tr>
<th colspan=""2""><H1>$CompanyName - Windows Server Backup Report</H1></th>
</tr>
<tr>
<th colspan=""2""><h3><b>$TheMachineName</b> Windows Server Backup Information</h3></th>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Today's date:</td>
<td style=""background-color:$CellBGColor;""><I>$CurrentTime</I></td>
</tr>
<tr>
<td>Last Successful Backup:</td>
<td><I>$WBLastSuccess</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Backup Result:</td>
<td style=""background-color:$CellBGColor;""><I>$WBResult</I></td>
</tr>
<tr>
<td>Error Message:</td>
<td><I>$WBErrorMsg</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Last Backup Target:</td>
<td style=""background-color:$CellBGColor;""><I>$WBTarget ($WBLable)</I></td>
</tr>
<tr>
<td>Number Of Versions:</td>
<td><I>$WBNoOfVersions</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Last Backup Start Time:</td>
<td style=""background-color:$CellBGColor;"">$WBStartTime</td>
</tr>
<tr>
<td>Last Backup Finish Time:</td>
<td>$WBEndTime</td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Last Backup Duration:</td>
<td style=""background-color:$CellBGColor;"">$WBDuration</td>
</tr>
<tr>
<td>Next Scheduled Backup:</td>
<td><I>$WBNextSchedule</I></td>
</tr>
<tr>
<th colspan=""2""><h3>Machine Information</h3></th>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Local Machine Name:</td>
<td style=""background-color:$CellBGColor;""><I>$TheMachineName</I></td>
</tr>
<tr>
<td>Local IP Address:</td>
<td><I>$LocalIP</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Local MAC Address:</td>
<td style=""background-color:$CellBGColor;""><I>$nwMacADD</I></td>
</tr>
<tr>
<td>External IP Address:</td>
<td><I>$myExternalIP</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Machine Up Time:</td>
<td style=""background-color:$CellBGColor;""><I>$Uptime</I></td>
</tr>
<tr>
<td>PowerShell Version:</td>
<td><I>$VarPsVersion</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">Physical or Virtual:</td>
<td style=""background-color:$CellBGColor;""><I>$MachineHardwareType</I></td>
</tr>
<tr>
<td>Profile Corruption:</td>
<td><I>$ProfileBak</I></td>
</tr>
<tr>
<td style=""background-color:$CellBGColor;"">SharePoint Upgrade Required:</td>
<td style=""background-color:$CellBGColor;""><I>$SPConfig</I></td>
</tr>
<tr>
<th colspan=""2""><h3>VSS Writers</h3></th>
</tr>
<td colspan=""2"">$VSSResults</td>
<tr>
<th colspan=""2""><h3>Media Usage</h3></th>
</tr>
</table>
$StorageInfo
</table>
<table class=""docHeader"" style=""width:100%"">
<tr>
<th colspan=""2""><h3>Items In Backup</h3></th>
</tr>
</table>
<div class=""BackupItem"">
$BackupItemHTML
</div>
</body>
</html>
")
# Prepare to email
$Pass = Get-Content "C:\Masters\WIN SERVER BACKUP SCRIPT\cred.txt" | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
$msg = new-object Net.Mail.MailMessage
$msg.IsBodyHTML = $TRUE
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $FromAddress
$msg.To.Add($ToAddress)
$msg.Subject = $ReportSubject
$msg.Body = $sb
# Format the date and time for the file.
$VarDateTime = (Get-Date -format "yyyy-MMMM-dd-dddd-HHmm")
# Note the extension for the $CleanOldReports
$OutPut = "$OutPutPath\$VarDateTime.html"
# The output folder - The parent folder of the $OutPut.
$TARGETDIR = (split-path $OutPut -Parent)
# If the output folder does not exist then create it.
IF (!(Test-Path -Path $TARGETDIR )) {New-Item -ItemType directory -Path $TARGETDIR}
#Output the report to a file.
"$sb" | Out-File "$OutPut"
# If $TRUE then open the backup report in your default web browser.
IF ($ShowReport -eq $TRUE) {"$OutPut" | invoke-expression}
# If $TRUE then email the report to backup operators.
IF ($SendEmail -eq $TRUE) {$smtp.Send($msg)}
Write-Host "Report Successfully Generated." -ForegroundColor green
# Run cleanup tasks. Only delete .html files form $TARGETDIR.
IF ($CleanOldReports -eq $true) {
FOREACH ($File IN Get-Childitem $TARGETDIR -Include "*.html" -Recurse | Where-object {$_.LastWriteTime -le (Get-Date).AddDays( - $CleanUpDays)}) {
IF ($null -ne $File) {
write-host "Deleting Old Log $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
}
}
}
}
GenerateTheReport
Start-Sleep 20
#timeout 20
*****************************************************************************
来源:https://stackoverflow.com/questions/61320211/powershell-wsb-script