Assistance needed with Powershell Script. Need my Windows 2012 Server to send a backup report everyday to our helpdesk

Good day

I need assistance with a powershell script or a new script that can send a backup report of Windows Server Backup to our helpdesk e-mail.  I will attach my files and the error that I am receiving when trying to execute the script.

Basically I have added a folder called Backup Report Script in the following directory:
C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script

The powershell script name = HM_PTA_Get-WSBReport.ps1

I get an error message as per Word attachment - Powershell execution error.docx  

I have also attached the Task Scheduler Screens as per Word Document - Task Scheduler Screens.docx

Specs of Server:
Intel Xeon CPU E5-2430 @ 2.20GHz (2 Processors)
16 GB Ram
Windows Server 2012 Standard 64-bit

Server Name:
hmpta

AD Domain:
homemakerspta.local

Please let me know if you require further details.

Kind Regards
Lourensvd
Powershell-execution-error.docx
Task-Scheduler-Screens.docx
Lourens van DykIT Technical ConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

D KumarCommented:
Looks like permission issue, What level access the user account have?
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Domain Admin
Enterprise Admin
Administrators
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
It looks like the failure is with the New-PSSession you're initiating with the server.

Try running the following from the machine you are trying to run the script from:
Test-WSMan -ComputerName hmpta.homemakerspta.local

Open in new window

This will test if the WinRM service is running (and accepting commands) on your server.

If it's not running (You will see more red if it's not), you can run the following command (as administrator) on the server:
winrm quickconfig

Open in new window

This will initiate the WinRM service and should open the necessary ports for communication.

After that, try running your script again.
0
Introducing the "443 Security Simplified" Podcast

This new podcast puts you inside the minds of leading white-hat hackers and security researchers. Hosts Marc Laliberte and Corey Nachreiner turn complex security concepts into easily understood and actionable insights on the latest cyber security headlines and trends.

Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Thank you for the reply.  I have run the commands in powershell as administrator on the server, but still get the same results.  I have attached my results in the document "Results-from-WinRM-test.docx".

Anything else I can try?
Results-from-WinRM-test.docx
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Just to be clear, are you running those PowerShell commands directly from the hmpta.homemakerspta.local server?
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Yes.  They only have the one server.  So I am running the script directly from the server.
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Do you mind sharing more details of your script? I'm curious why you're using new-pssession if the script is being ran locally.
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy
Sure no problem.  Herewith the script that I use:


        [Parameter(Mandatory=$false,Position=0)]
        [ValidateNotNullOrEmpty()]
        [string]$ServerList="\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt",
        [Parameter(Mandatory=$false,Position=1)]
        [ValidateNotNullOrEmpty()]
        [string]$ReportPath="\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\Daily Reports",
        [Parameter(Mandatory=$false,Position=2)]
        [ValidateNotNullOrEmpty()]
        [string]$SMTPServer="197.221.10.28",
        [Parameter(Mandatory=$false,Position=3)]
        [ValidateNotNullOrEmpty()]
        [string[]$Recipient="homemakers@broadvision.co.za",
        [Parameter(Mandatory=$false,Position=4)]
        [ValidateNotNullOrEmpty()]
        [string]$Sender="HMPTA@homemakers-sa.co.za",
        [Parameter(Mandatory=$false,Position=5)]
        [ValidateNotNullOrEmpty()]
        [string]$Username="test2@compnet.co.za",
        [Parameter(Mandatory=$false,Position=6)]
        [ValidateNotNullOrEmpty()]
        [string]$Password="Compnet2014",
        [Parameter(Mandatory=$false,Position=7)]
        [ValidateSet("True","False")]
        [string[]$SSL="False",
        [Parameter(Mandatory=$false,Position=8)]
        [ValidateNotNullOrEmpty()]
        [int]$Port=587
    )
$timestamp = Get-Date -format yyyy-MM-dd-HH

#Check if server list exists
If (!(Test-Path $ServerList)){
    Write-Host "Can not get servers list. Script will not continue" -ForegroundColor Red;Exit}

$servers = @()

Get-Content $ServerList | Foreach-Object {$servers+=$_}

$results = (1..$servers.length)

for ($i=0; $i -lt $servers.length; $i++)
    {
        $ConnectionError=0
          Write-Host "Getting result from server: " $servers[$i]
        try{
        $Session = New-PSSession -ComputerName $servers[$i]
        $WindowsVersion = Invoke-Command -session $session -ScriptBlock {(Get-WmiObject win32_operatingsystem).version}
        if ($WindowsVersion -match "6.1")
            {$WBSummary = Invoke-Command -session $session -ScriptBlock {add-pssnapin windows.serverbackup;Get-WBSummary}}
        else {$WBSummary = Invoke-Command -session $session -ScriptBlock {Get-WBSummary}}
        Remove-PSSession $Session
            }catch
                {
                    Write-Host "Error connecting remote server"
                    write-host "Caught an exception:" -ForegroundColor Red
                    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
                    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
                    $ConnectionError=1
                }
             
        #Storing results
        $results[$i] = New-Object Collections.Arraylist
       
        $results[$i].add("<td>" + $servers[$i] + "</td>") > $null

        if ($ConnectionError -eq 1)
            {
             $results[$i].add("<td><b><font color=red>Unknown</font></b></td>") > $null
             $results[$i].add("<td>" + "Unknown" + "</td>") > $null
             $results[$i].add("<td>" + "Error connecting remote server" + "</td>") > $null
            }
        else
            {
             if ($WBSummary.LastBackupResultHR -eq 0) {$results[$i].add("<td><b><font color=green>Success</font></b></td>") > $null;$result="Success"}
             else {$results[$i].add("<td><b><font color=red>Failure</font></b></td>") > $null;$result="Failure"}
       
             $results[$i].add("<td>" + $WBSummary.LastSuccessfulBackupTime + "</td>") > $null
   
             if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)){$results[$i].add("<td>Success</td>") > $null;$message="Sucess"}
             else{$results[$i].add("<td>" + $WBSummary.DetailedMessage + "</td>") > $null;$message= $WBSummary.DetailedMessage}
       
       
             Write-Host "Last Backup Result: $result"
             Write-Host "Last Successful Backup Time: " $WBSummary.LastSuccessfulBackupTime
             Write-Host "Detailed Message: $message"
             Write-Host "-----------------------------------------------------------------"
            }
    }

if ([boolean](get-variable "rows" -ErrorAction SilentlyContinue))
    {Clear-Variable -Name "rows" -Scope Global}

for ($i=0; $i -lt $servers.length; $i++)
    {
        $rows=$rows +"<tr>" + $results[$i] + "</tr>"
    }

$HTMLFile = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<style>TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#99CCFF}
    TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#E0F5FF}
</style>
</head>
<body>
<H1>Homemakers PTA Windows Server Backup Status</H1>
<table>
    <tr>
        <th>Server</th>
        <th>Last Backup Result</th>
        <th>Last Backup Result Time</th>
        <th>Message</th>
    </tr>
        $rows
</table>
</body>
</html>
"@
if ([boolean](get-variable "ReportPath" -ErrorAction SilentlyContinue))
    {Clear-Variable -Name "ReportPath" -Scope Global}
$ReportPath = $ReportPath + "$timestamp" + "_WSBReport.html"
try{
ConvertTo-HTML -Body $HTMLFile -title "Windows Server Backup Report" | Out-File $ReportPath
    }catch
         {
          Write-Host "Error storing htlm report" -ForegroundColor Red
          write-host "Caught an exception:" -ForegroundColor Red
          write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
          write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
         }
# Mail sending  
if($SMTPServer -ne "None")
    {
        #Creating a Mail object
        $msg = new-object Net.Mail.MailMessage

        #Creating SMTP server object
        $smtp = new-object Net.Mail.SmtpClient($SMTPServer,$Port)

        #Email structure
        $msg.From = $Sender
        $msg.ReplyTo = $Sender
        ForEach($mail in $Recipient)
        {
            $msg.To.Add($mail)
        }
        if ($Username -ne "None" -and $Password -ne "None")
            {
                $smtp.Credentials = new-object System.Net.NetworkCredential($Username, $Password)
            }
        if ($SSL -ne "False")
            {
                $smtp.EnableSsl = $true
            }
        #Email subject
        $msg.subject = "Homemakers PTA Windows Backup"
        #Email body
        $msg.body = $HTMLFile
        $msg.IsBodyHtml = $true
        #Sending email
        try{
            Write-Output "Sending email"
            $smtp.Send($msg)
           }catch
                {
                    Write-Host "Error sending email" -ForegroundColor Red
                    write-host "Caught an exception:" -ForegroundColor Red
                    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
                    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
                }
     }
 

Please check and let me know.  If you have a simpler or working script that I can use, then we can try that.  Open for any suggestions.
Kind Regards
Lourensvd
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
It looks like this script is pulling from a list of servers:
"\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt"

Open in new window


Since you say there is only one server, is it safe to assume that the only entry in the 'servbackup.txt' file is: hmpta.homemakerspta.local
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Yes that is correct.  Only hmpta.homemakerspta.local is listed in the servbackup.txt' file
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
I've made a few tweaks... Give this a shot.
param(
    [Parameter(Mandatory = $false, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$ServerList = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt",
    [Parameter(Mandatory = $false, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$ReportPath = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\Daily Reports",
    [Parameter(Mandatory = $false, Position = 2)]
    [ValidateNotNullOrEmpty()]
    [string]$SMTPServer = "197.221.10.28",
    [Parameter(Mandatory = $false, Position = 3)]
    [ValidateNotNullOrEmpty()]
    [string[]$Recipient = "homemakers@broadvision.co.za",
    [Parameter(Mandatory = $false, Position = 4)]
    [ValidateNotNullOrEmpty()]
    [string]$Sender = "HMPTA@homemakers-sa.co.za",
    [Parameter(Mandatory = $false, Position = 5)]
    [ValidateNotNullOrEmpty()]
    [string]$Username = "test2@compnet.co.za",
    [Parameter(Mandatory = $false, Position = 6)]
    [ValidateNotNullOrEmpty()]
    [string]$Password = "Compnet2014",
    [Parameter(Mandatory = $false, Position = 7)]
    [ValidateSet("True", "False")]
    [string[]$SSL = "False",
    [Parameter(Mandatory = $false, Position = 8)]
    [ValidateNotNullOrEmpty()]
    [int]$Port = 587
)
$timestamp = Get-Date -format yyyy-MM-dd-HH


$ConnectionError = 0
Write-Host "Getting result from server: "
try {
    $WindowsVersion = (Get-WmiObject win32_operatingsystem).version
    if ($WindowsVersion -match "6.1") {
        $WBSummary = add-pssnapin windows.serverbackup; Get-WBSummary
    }
    else {
        $WBSummary = Invoke-Command -session $session -ScriptBlock {Get-WBSummary}
    }
    Remove-PSSession $Session
}
catch {
    Write-Host "Error gathering server data"
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    $ConnectionError = 1
}
        
#Storing results
$results = New-Object Collections.Arraylist

$results.add("<td>" + $env:COMPUTERNAME + "</td>") > $null

if ($ConnectionError -eq 1) {
    $results.add("<td><b><font color=red>Unknown</font></b></td>") > $null
    $results.add("<td>" + "Unknown" + "</td>") > $null
    $results.add("<td>" + "Error connecting remote server" + "</td>") > $null
}
else {
    if ($WBSummary.LastBackupResultHR -eq 0) {$results.add("<td><b><font color=green>Success</font></b></td>") > $null; $result = "Success"}
    else {$results.add("<td><b><font color=red>Failure</font></b></td>") > $null; $result = "Failure"}

    $results.add("<td>" + $WBSummary.LastSuccessfulBackupTime + "</td>") > $null

    if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)) {$results.add("<td>Success</td>") > $null; $message = "Sucess"}
    else {$results.add("<td>" + $WBSummary.DetailedMessage + "</td>") > $null; $message = $WBSummary.DetailedMessage}


    Write-Host "Last Backup Result: $result"
    Write-Host "Last Successful Backup Time: " $WBSummary.LastSuccessfulBackupTime
    Write-Host "Detailed Message: $message"
    Write-Host "-----------------------------------------------------------------"
}

$rows = "<tr>" + $results + "</tr>"

$HTMLFile = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<style>TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#99CCFF}
    TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#E0F5FF}
</style>
</head>
<body>
<H1>Homemakers PTA Windows Server Backup Status</H1>
<table>
    <tr>
        <th>Server</th>
        <th>Last Backup Result</th>
        <th>Last Backup Result Time</th>
        <th>Message</th>
    </tr>
        $rows
</table>
</body>
</html>
"@
if (!(Test-Path -Path $ReportPath)) {
    try {
        New-Item -Path $ReportPath -ItemType Directory
    }
    catch {
        Write-Host "Unable to create directory $ReportPath"
        Write-Host "Storing reports locally..."
        $ReportPath = Join-Path -path $env:ProgramData -ChildPath "WBS Logs"
        if (!(Test-Path $ReportPath)) {
            New-Item -Path $ReportPath -ItemType Directory
        }
    }
}
$ReportFile = Join-Path -Path $ReportPath -ChildPath "$($timestamp)_WSBReport.html"
try {
    ConvertTo-HTML -Body $HTMLFile -title "Windows Server Backup Report" | Out-File $ReportFile
}
catch {
    Write-Host "Error storing htlm report" -ForegroundColor Red
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
# Mail sending  
if ($SMTPServer -ne "None") {
    #Creating a Mail object
    $msg = new-object Net.Mail.MailMessage

    #Creating SMTP server object
    $smtp = new-object Net.Mail.SmtpClient($SMTPServer, $Port)

    #Email structure
    $msg.From = $Sender
    $msg.ReplyTo = $Sender
    ForEach ($mail in $Recipient) {
        $msg.To.Add($mail)
    }
    if ($Username -ne "None" -and $Password -ne "None") {
        $smtp.Credentials = new-object System.Net.NetworkCredential($Username, $Password)
    }
    if ($SSL -ne "False") {
        $smtp.EnableSsl = $true
    }
    #Email subject
    $msg.subject = "Homemakers PTA Windows Backup"
    #Email body
    $msg.body = $HTMLFile
    $msg.IsBodyHtml = $true
    #Sending email
    try {
        Write-Output "Sending email"
        $smtp.Send($msg)
    }
    catch {
        Write-Host "Error sending email" -ForegroundColor Red
        write-host "Caught an exception:" -ForegroundColor Red
        write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
        write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    }
}

Open in new window

0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
I eliminated the looping through a list of servers, since you're only processing the one.
I also eliminated the use of PSSessions, since the script is being ran locally, there is no need for them.
I created a fallback location for log files in ProgramData\Logs (Assuming the caller of the script has the right level of access to create the directory).
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Thank you for the script.  I have created a new one with your code.  Now I am getting the following error in Powershell when tring to execute:

PS C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script> C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script\HM_PTA_Get-WSBReport.ps1

At C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script\HM_PTA_Get-WSBReport.ps1:13 char:13
+     [string[]$Recipient = "homemakers@broadvision.co.za",
+             ~
Missing ] at end of attribute or type literal.
At C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script\HM_PTA_Get-WSBReport.ps1:25 char:13
+     [string[]$SSL = "False",
+             ~
Missing ] at end of attribute or type literal.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EndSquareBracketExpectedAtEndOfAttribute

I have added screenshot in Word document attached.  At least less red, so it looks good thus far.
Please advise.
Kind Regards
Modified-PS-Script.docx
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy
 
I have managed to modify the brackets:
+     [string[]$Recipient = "homemakers@broadvision.co.za",
to
+     [string]$Recipient = "homemakers@broadvision.co.za",
and
+     [string[]$SSL = "False",
to
+     [string]$SSL = "False",

This helped to remove the PS Error I was getting, but now I am getting this error:

Getting result from server:
Error gathering server data
Caught an exception:
Exception Type: System.Management.Automation.ParameterBindingValidationException
Exception Message: Cannot validate argument on parameter 'Session'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.

Sending email
Error sending email
Caught an exception:
Exception Type: System.Management.Automation.MethodInvocationException
Exception Message: Exception calling "Send" with "1" argument(s): "Failure sending mail."

Have attached the screenshot in Word.
Modified-PS-Script2.docx
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Here we go, this should do the trick! :)

param(
    [Parameter(Mandatory = $false, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$ServerList = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt",
    [Parameter(Mandatory = $false, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$ReportPath = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\Daily Reports",
    [Parameter(Mandatory = $false, Position = 2)]
    [ValidateNotNullOrEmpty()]
    [string]$SMTPServer = "197.221.10.28",
    [Parameter(Mandatory = $false, Position = 3)]
    [ValidateNotNullOrEmpty()]
    [string]$Recipient = "homemakers@broadvision.co.za",
    [Parameter(Mandatory = $false, Position = 4)]
    [ValidateNotNullOrEmpty()]
    [string]$Sender = "HMPTA@homemakers-sa.co.za",
    [Parameter(Mandatory = $false, Position = 5)]
    [ValidateNotNullOrEmpty()]
    [string]$Username = "test2@compnet.co.za",
    [Parameter(Mandatory = $false, Position = 6)]
    [ValidateNotNullOrEmpty()]
    [string]$Password = "Compnet2014",
    [Parameter(Mandatory = $false, Position = 7)]
    [ValidateSet("True", "False")]
    [string]$SSL = "False",
    [Parameter(Mandatory = $false, Position = 8)]
    [ValidateNotNullOrEmpty()]
    [int]$Port = 587
)
$timestamp = Get-Date -format yyyy-MM-dd-HH


$ConnectionError = 0
Write-Host "Getting result from server: "
try {
    $WindowsVersion = (Get-WmiObject win32_operatingsystem).version
    if ($WindowsVersion -match "6.1") {
        $WBSummary = add-pssnapin windows.serverbackup; Get-WBSummary
    }
    else {
        $WBSummary = Get-WBSummary
    }
}
catch {
    Write-Host "Error gathering server data"
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    $ConnectionError = 1
}
        
#Storing results
$results = New-Object Collections.Arraylist

$results.add("<td>" + $env:COMPUTERNAME + "</td>") > $null

if ($ConnectionError -eq 1) {
    $results.add("<td><b><font color=red>Unknown</font></b></td>") > $null
    $results.add("<td>" + "Unknown" + "</td>") > $null
    $results.add("<td>" + "Error connecting remote server" + "</td>") > $null
}
else {
    if ($WBSummary.LastBackupResultHR -eq 0) {$results.add("<td><b><font color=green>Success</font></b></td>") > $null; $result = "Success"}
    else {$results.add("<td><b><font color=red>Failure</font></b></td>") > $null; $result = "Failure"}

    $results.add("<td>" + $WBSummary.LastSuccessfulBackupTime + "</td>") > $null

    if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)) {$results.add("<td>Success</td>") > $null; $message = "Sucess"}
    else {$results.add("<td>" + $WBSummary.DetailedMessage + "</td>") > $null; $message = $WBSummary.DetailedMessage}


    Write-Host "Last Backup Result: $result"
    Write-Host "Last Successful Backup Time: " $WBSummary.LastSuccessfulBackupTime
    Write-Host "Detailed Message: $message"
    Write-Host "-----------------------------------------------------------------"
}

$rows = "<tr>" + $results + "</tr>"

$HTMLFile = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<style>TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#99CCFF}
    TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#E0F5FF}
</style>
</head>
<body>
<H1>Homemakers PTA Windows Server Backup Status</H1>
<table>
    <tr>
        <th>Server</th>
        <th>Last Backup Result</th>
        <th>Last Backup Result Time</th>
        <th>Message</th>
    </tr>
        $rows
</table>
</body>
</html>
"@
if (!(Test-Path -Path $ReportPath)) {
    try {
        New-Item -Path $ReportPath -ItemType Directory
    }
    catch {
        Write-Host "Unable to create directory $ReportPath"
        Write-Host "Storing reports locally..."
        $ReportPath = Join-Path -path $env:ProgramData -ChildPath "WBS Logs"
        if (!(Test-Path $ReportPath)) {
            New-Item -Path $ReportPath -ItemType Directory
        }
    }
}
$ReportFile = Join-Path -Path $ReportPath -ChildPath "$($timestamp)_WSBReport.html"
try {
    ConvertTo-HTML -Body $HTMLFile -title "Windows Server Backup Report" | Out-File $ReportFile
}
catch {
    Write-Host "Error storing htlm report" -ForegroundColor Red
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
Send-MailMessage -SmtpServer $SMTPServer -Body $HTMLFile -BodyAsHtml -Subject "Homemakers PTA Windows Backup" -To $Recipient -From $Sender -Credential $Creds

Open in new window

0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Thank you.  The script is now executing when running it in elevated powershell and my e-mail is being received in the helpdesk.  I just need to check that it runs automatically via Task Scheduler.

I do however get this result:
Last Backup result = unknown / Last Backup Result Time = unknown
I have attached the results

Do you know what this could be?
html-file-status.docx
2018-06-18-16_WSBReport.html
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
It looks like the breakdown now is with running the Get-WBSummary command, or with the serverbackup pssnapin. Can you copy/paste the following into a powershell console on the server and see what error it gives?

    if ($WindowsVersion -match "6.1") {
        $WBSummary = add-pssnapin windows.serverbackup; Get-WBSummary
    }
    else {
        $WBSummary = Get-WBSummary
    }

Open in new window

0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy
If I open Power Shell in Elevated command prompt and try to run the script I do not get any error message and my screen would look like in attachment:  Powershell as administrator.doc

PS C:\Users\broadvision\Documents> C:\Users\broadvision\Documents\BS Summary.ps1

Get-WBSummary : The Windows Server Backup engine is not accessible. Make sure that you are a member of the Administrators or Backup Operators group on the computer and the
Windows PowerShell session is opened with elevated rights.
At C:\Users\broadvision\Documents\BS Summary.ps1:5 char:22
+         $WBSummary = Get-WBSummary
+                      ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-WBSummary], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.Windows.ServerBackup.Commands.GetWBSummary

The same happens when I try to edit and run our backup script in Powershell ISE

PS C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script> C:\Windows\SYSVOL\sysvol\homemakerspta.local\scripts\Backup Report Script\HM_PTA_Get-WSBReport.ps1

Getting result from server:
Error gathering server data
Caught an exception:
Exception Type: System.Exception
Exception Message: The Windows Server Backup engine is not accessible. Make sure that you are a member of the Administrators or Backup Operators group on the computer and the
Windows PowerShell session is opened with elevated rights.

It does however send the mail to helpdesk even with the error in powershell.  Don't know if it might have to do with the same issue.
Powershell-as-Administrator.docx
error-when-testing-in-Powershell-IS.docx
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Hmm, let's try the following:
Open PowerShell as Administrator (Elevated)
Type: Get-WBSummary then press Enter.
Post the output here
0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy
Herewith the output in Elevated Powershell:
Get-WBSummary

NextBackupTime                  : 6/19/2018 9:00:00 PM
NumberOfVersions                : 921
LastSuccessfulBackupTime        : 6/18/2018 9:00:16 PM
LastSuccessfulBackupTargetPath  : \\?\Volume{f11706ab-5e63-411c-8866-4511c0501d30}
LastSuccessfulBackupTargetLabel : HMPTA 2017_03_13 14:50 DISK_01
LastBackupTime                  : 6/18/2018 9:00:16 PM
LastBackupTarget                : HMPTA 2017_03_13 14:50 DISK_01
DetailedMessage                 :
LastBackupResultHR              : 0
LastBackupResultDetailedHR      : 0
CurrentOperationStatus          : NoOperationInProgress
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Ok, made a minor tweak to the script. Please try saving this code in a script and running it (as Admin).
param(
    [Parameter(Mandatory = $false, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$ServerList = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt",
    [Parameter(Mandatory = $false, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$ReportPath = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\Daily Reports",
    [Parameter(Mandatory = $false, Position = 2)]
    [ValidateNotNullOrEmpty()]
    [string]$SMTPServer = "197.221.10.28",
    [Parameter(Mandatory = $false, Position = 3)]
    [ValidateNotNullOrEmpty()]
    [string]$Recipient = "homemakers@broadvision.co.za",
    [Parameter(Mandatory = $false, Position = 4)]
    [ValidateNotNullOrEmpty()]
    [string]$Sender = "HMPTA@homemakers-sa.co.za",
    [Parameter(Mandatory = $false, Position = 5)]
    [ValidateNotNullOrEmpty()]
    [string]$Username = "test2@compnet.co.za",
    [Parameter(Mandatory = $false, Position = 6)]
    [ValidateNotNullOrEmpty()]
    [string]$Password = "Compnet2014",
    [Parameter(Mandatory = $false, Position = 7)]
    [ValidateSet("True", "False")]
    [string]$SSL = "False",
    [Parameter(Mandatory = $false, Position = 8)]
    [ValidateNotNullOrEmpty()]
    [int]$Port = 587
)
$timestamp = Get-Date -format yyyy-MM-dd-HH


$ConnectionError = 0
Write-Host "Getting result from server: "
try {
    $WBSummary = Get-WBSummary
}
catch {
    Write-Host "Error gathering server data"
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    $ConnectionError = 1
}
        
#Storing results
$results = New-Object Collections.Arraylist

$results.add("<td>" + $env:COMPUTERNAME + "</td>") > $null

if ($ConnectionError -eq 1) {
    $results.add("<td><b><font color=red>Unknown</font></b></td>") > $null
    $results.add("<td>" + "Unknown" + "</td>") > $null
    $results.add("<td>" + "Error connecting remote server" + "</td>") > $null
}
else {
    if ($WBSummary.LastBackupResultHR -eq 0) {$results.add("<td><b><font color=green>Success</font></b></td>") > $null; $result = "Success"}
    else {$results.add("<td><b><font color=red>Failure</font></b></td>") > $null; $result = "Failure"}

    $results.add("<td>" + $WBSummary.LastSuccessfulBackupTime + "</td>") > $null

    if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)) {$results.add("<td>Success</td>") > $null; $message = "Sucess"}
    else {$results.add("<td>" + $WBSummary.DetailedMessage + "</td>") > $null; $message = $WBSummary.DetailedMessage}


    Write-Host "Last Backup Result: $result"
    Write-Host "Last Successful Backup Time: " $WBSummary.LastSuccessfulBackupTime
    Write-Host "Detailed Message: $message"
    Write-Host "-----------------------------------------------------------------"
}

$rows = "<tr>" + $results + "</tr>"

$HTMLFile = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<style>TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#99CCFF}
    TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#E0F5FF}
</style>
</head>
<body>
<H1>Homemakers PTA Windows Server Backup Status</H1>
<table>
    <tr>
        <th>Server</th>
        <th>Last Backup Result</th>
        <th>Last Backup Result Time</th>
        <th>Message</th>
    </tr>
        $rows
</table>
</body>
</html>
"@
if (!(Test-Path -Path $ReportPath)) {
    try {
        New-Item -Path $ReportPath -ItemType Directory
    }
    catch {
        Write-Host "Unable to create directory $ReportPath"
        Write-Host "Storing reports locally..."
        $ReportPath = Join-Path -path $env:ProgramData -ChildPath "WBS Logs"
        if (!(Test-Path $ReportPath)) {
            New-Item -Path $ReportPath -ItemType Directory
        }
    }
}
$ReportFile = Join-Path -Path $ReportPath -ChildPath "$($timestamp)_WSBReport.html"
try {
    ConvertTo-HTML -Body $HTMLFile -title "Windows Server Backup Report" | Out-File $ReportFile
}
catch {
    Write-Host "Error storing htlm report" -ForegroundColor Red
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
Send-MailMessage -SmtpServer $SMTPServer -Body $HTMLFile -BodyAsHtml -Subject "Homemakers PTA Windows Backup" -To $Recipient -From $Sender -Credential $Creds

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy

Here is the results from the script.  Copy and paste in Powershell Run as Administrator

Error gathering server data
Caught an exception:
Exception Type: System.Management.Automation.CommandNotFoundException
Exception Message: The term 'Get-WBSummary' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I have attached the word document = Modified PS Script 3 results.docx as screenshot
Modified-PS-Script-3-results.docx
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Woops, looks like we need to import the wbs cmdlet.
I've added the following to the script, just after the parameters
Add-PSSnapin -Name Windows.ServerBackup
Get-Command -Module Windows.ServerBackup

Open in new window


param(
    [Parameter(Mandatory = $false, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string]$ServerList = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\servbackup.txt",
    [Parameter(Mandatory = $false, Position = 1)]
    [ValidateNotNullOrEmpty()]
    [string]$ReportPath = "\\homemakerspta.local\SYSVOL\homemakerspta.local\scripts\Backup Report Script\Daily Reports",
    [Parameter(Mandatory = $false, Position = 2)]
    [ValidateNotNullOrEmpty()]
    [string]$SMTPServer = "197.221.10.28",
    [Parameter(Mandatory = $false, Position = 3)]
    [ValidateNotNullOrEmpty()]
    [string]$Recipient = "homemakers@broadvision.co.za",
    [Parameter(Mandatory = $false, Position = 4)]
    [ValidateNotNullOrEmpty()]
    [string]$Sender = "HMPTA@homemakers-sa.co.za",
    [Parameter(Mandatory = $false, Position = 5)]
    [ValidateNotNullOrEmpty()]
    [string]$Username = "test2@compnet.co.za",
    [Parameter(Mandatory = $false, Position = 6)]
    [ValidateNotNullOrEmpty()]
    [string]$Password = "Compnet2014",
    [Parameter(Mandatory = $false, Position = 7)]
    [ValidateSet("True", "False")]
    [string]$SSL = "False",
    [Parameter(Mandatory = $false, Position = 8)]
    [ValidateNotNullOrEmpty()]
    [int]$Port = 587
)

Add-PSSnapin -Name Windows.ServerBackup
Get-Command -Module Windows.ServerBackup

$timestamp = Get-Date -format yyyy-MM-dd-HH


$ConnectionError = 0
Write-Host "Getting result from server: "
try {
    $WBSummary = Get-WBSummary
}
catch {
    Write-Host "Error gathering server data"
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
    $ConnectionError = 1
}
        
#Storing results
$results = New-Object Collections.Arraylist

$results.add("<td>" + $env:COMPUTERNAME + "</td>") > $null

if ($ConnectionError -eq 1) {
    $results.add("<td><b><font color=red>Unknown</font></b></td>") > $null
    $results.add("<td>" + "Unknown" + "</td>") > $null
    $results.add("<td>" + "Error connecting remote server" + "</td>") > $null
}
else {
    if ($WBSummary.LastBackupResultHR -eq 0) {$results.add("<td><b><font color=green>Success</font></b></td>") > $null; $result = "Success"}
    else {$results.add("<td><b><font color=red>Failure</font></b></td>") > $null; $result = "Failure"}

    $results.add("<td>" + $WBSummary.LastSuccessfulBackupTime + "</td>") > $null

    if ([string]::IsNullOrEmpty($WBSummary.DetailedMessage)) {$results.add("<td>Success</td>") > $null; $message = "Sucess"}
    else {$results.add("<td>" + $WBSummary.DetailedMessage + "</td>") > $null; $message = $WBSummary.DetailedMessage}


    Write-Host "Last Backup Result: $result"
    Write-Host "Last Successful Backup Time: " $WBSummary.LastSuccessfulBackupTime
    Write-Host "Detailed Message: $message"
    Write-Host "-----------------------------------------------------------------"
}

$rows = "<tr>" + $results + "</tr>"

$HTMLFile = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<style>TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
    TH{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#99CCFF}
    TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:#E0F5FF}
</style>
</head>
<body>
<H1>Homemakers PTA Windows Server Backup Status</H1>
<table>
    <tr>
        <th>Server</th>
        <th>Last Backup Result</th>
        <th>Last Backup Result Time</th>
        <th>Message</th>
    </tr>
        $rows
</table>
</body>
</html>
"@
if (!(Test-Path -Path $ReportPath)) {
    try {
        New-Item -Path $ReportPath -ItemType Directory
    }
    catch {
        Write-Host "Unable to create directory $ReportPath"
        Write-Host "Storing reports locally..."
        $ReportPath = Join-Path -path $env:ProgramData -ChildPath "WBS Logs"
        if (!(Test-Path $ReportPath)) {
            New-Item -Path $ReportPath -ItemType Directory
        }
    }
}
$ReportFile = Join-Path -Path $ReportPath -ChildPath "$($timestamp)_WSBReport.html"
try {
    ConvertTo-HTML -Body $HTMLFile -title "Windows Server Backup Report" | Out-File $ReportFile
}
catch {
    Write-Host "Error storing htlm report" -ForegroundColor Red
    write-host "Caught an exception:" -ForegroundColor Red
    write-host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
    write-host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red
}
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
Send-MailMessage -SmtpServer $SMTPServer -Body $HTMLFile -BodyAsHtml -Subject "Homemakers PTA Windows Backup" -To $Recipient -From $Sender -Credential $Creds

Open in new window

0
Lourens van DykIT Technical ConsultantAuthor Commented:
Hi Timothy
Hope you are well.  I did some troubleshooting on why the script did not execute even though it works perfectly when running it via administrator in Powershell.  Here are some things I did to make your script execute in the administrative profile (in my case broadvision account)

When running the script normally, I would get errors in red and also when trying to run it automated via Task Scheduler, I would get this error message via Task Scheduler Incorrect function. (0x80070001). When researching the problem, I used the following steps to correct the problem.  

I decided to enable administrator account first, Reset password and log in via administrator.  I still got the same message in Task Scheduler.
So I decided to copy all the contents of our folder “Backup Report Script” containing HM_PTA_Get-WSBReport.ps1, Daily Reports folder and servbackup.txt file to C:\Scripts
Checked File association and found that my *.ps1 extensions was associated with notepad.  Corrected to point to C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Deleted and re-created my Scheduled Task as per word document:     Task Scheduler Settings for perfect execution.docx
Also just make sure that administrators and your administrative account in my case “broadvision” account has full control on these folders.
After checking all these settings, I ran the task as administrator first to verify that it is working.  Then changed it to the administrative account “broadvision”
All this done in administrator profile and logged back into the “broadvision” account and the script executed perfectly and through Task Scheduler.

Thank you again Timothy for your script, advice, determination and patience in getting the problem sorted.  If these steps did not work, then I would have made your final modifications to the script.  Well done. (Thumbs up)
Task-Scheduler-Settings-for-perfect.docx
0
Lourens van DykIT Technical ConsultantAuthor Commented:
I Reward my points to Timothy for the script and would just make sure that my prerequisites in my final place is in place.
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
You're welcome Lourens! Happy to help :)

Glad you were able to get the everything sorted out and functional!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.