Solved

need assistance with a technet script

Posted on 2014-12-25
17
159 Views
Last Modified: 2014-12-28
need assistance with this TechNet script, the script runs fine, but outputs only into the powershell window.

how can we modify this script so that the results are emailed, ideally in the body of the email, but as an attachment would also work.
if there is anyway to output this into a nicely formatted HTML view, that would be excellent.

here is the script:
########################################
#Get-ADForestHealth V2
#By Winston McMiller
#Synoposis: script leverages Repadmin.exe and DCdiag.exe across the entire forest or domain to help analysis and troubleshooting. 


Param(
  [string]$filePath,
  [string]$Domain,
  [Switch]$Report
    )

$local = $env:Computername + "."+ $env:Userdnsdomain


Function WMIDateStringToDate($Bootup) {  
    [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup)  
} 

Function Get-ForestDNSAnalysis_Local{

                $adreporttxt = "ADREPORT for" + $domain + (Get-Date -Format M.d.yyyy.hh.mm.ss) +".txt"          
                $Dcdiag= dcdiag /test:DNS /v
                $DNSLog= $dcDiag -like "*invalid DNS server*" 
				$SRVLog= $dcDiag -like "*Missing SRV record*"
				$SRVLog2=$dcDiag -like "*Error details: 9003*"
                $CFLOG= $dcDiag -like "*Missing A record at DNS server*"
				$REP=repadmin /replsummary
                $w32tm = w32tm /monitor /computers:$dc /nowarn
                $icmp = ($w32tm -like "*ICMP*") -replace "ICMP:",""
                
                If($icmp -le "0ms"){$timestatus="Optimal"}
                IF($icmp -gt "300000ms"){$timestatus="Critical. Over 5 mins!"}
                If($icmp -gt "100000ms"){$timestatus="Possible Drift Warning"}
                
                $CPULOAD= Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average 
                $Systems = Get-WMIObject -class Win32_OperatingSystem -computer $dc  
                $NIC=Get-wmiobject -class Win32_NetworkAdapterConfiguration -filter "IPEnabled=True"
                $ComputerIP = $nic.IPaddress[0] 
				$dnsServers = $nic.dnsserversearchorder 
                              
                                foreach ($system in $Systems) {  
                                   $Bootup = $system.LastBootUpTime  
                                   $LastBootUpTime = WMIDateStringToDate $bootup  
                                   $now = Get-Date
                                   $Uptime = $now - $lastBootUpTime  
                                                               }                                                              
                                                    
                		$unreachableServers = foreach ($d in $dnsServers) {
						    try { 
				        if ((-not (Get-Service -Name Dns -ComputerName  $d -ErrorAction SilentlyContinue))  -as [Bool]) {
						        $d
						}
						    } catch {
						         $d
						    }
						    }

							    $ADreports=New-Object PSObject -Property @{
							    HasInvalidDNSServerIPs = $($unreachableServers -as [bool])
							    MissingSrvRecords = $($srvLog -as [bool])
							    MissingARecord = $($cflog -as [bool])
							    DnsServerSearchOrder= ($dnsServers -join ([Environment]::Newline))
							    Unreachable_DNS_ServersIP = ($unreachableServers -join ([Environment]::Newline))
                                Computer_IP_Address = $ComputerIP
							    ComputerName = $DC
                                Time_Status = $timestatus
                                Time_Sync = $ICMP
                                Last_Bootup = $LastBootUpTime
                                AverageCPULoad= $CPULOAD.Average
                                Replication_Summary= ( $rep -replace "Beginning data collection for replication summary, this may take awhile:" -join ([Environment]::Newline))}                         
                                
                                $adreports                                
                                             
              If($srvlog){
              Write-Host "Repairing Missing SRV record on $DC" -ForegroundColor Green
              nltest /dsregdns
              $Repadmin=Repadmin /syncall
                         }
                         
              $Nltest
              If($Nltest -like "*ERROR_NO_TRUST_SAM_ACCOUNT*"){
              test-computersecurechannel -repair
                                                              } 
                                                              
              If($timestatus = "Critical. Over 5 mins!"){
              w32tm /config /update
              w32tm /resync
              Stop-Service -Name w32time
              Start-Service -Name w32time
              Get-Date -Format hh.mm.ss
              Write-Host "Time Service configured for $DC...." -ForegroundColor Green 
              }                                                
              
              If($unreachableServers){
              Write-Host "Bad DNS IP:$unreachableServers on $DC" -ForegroundColor Green
  
              $title = "Delete the misconfigured IP"
              $message = "Do you want to delete the misconfigured IP from $DC? "

              $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
                     "Deletes the misconfigured IP from the DNS search order."

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Retains the DNS search order."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

switch ($result)
    {
        0 {"You selected Yes."}
        1 {"You selected No."}
    }
If($result=0){
              netsh interface ipv4 delete dnsservers "local area Connection" $unreachableServers
              netsh interface ipv4 show dnsservers "local area Connection"
              $Repadmin
              }
                
               Write-Host "_______________________________________________________________________________________________________" -ForegroundColor Blue
               Write-Host " "
  }   
             IF($Report){$adreports >> $adreporttxt}  
  }                     

Function Get-ForestDNSAnalysis{
                
                $adreporttxt= "ADREPORT for" + $domain + (Get-Date -Format M.d.yyyy.hh.mm.ss) +".txt"  
                $Dcdiag = invoke-command -computername $DC -scriptblock {dcdiag /test:DNS /v}
                $DNSLog= $dcDiag -like "*invalid DNS server*" 
				$SRVLog= $dcDiag -like "*Missing SRV record*"
				$SRVLog2=$dcDiag -like "*Error details: 9003*"
				$CFLOG= $dcDiag -like "*Missing A record at DNS server*"
				$REP = invoke-command -computername $DC -scriptblock {repadmin /replsummary | where {$_ -ne ""}}
                $w32tm = invoke-command -computername $DC -scriptblock{w32tm /monitor /computers:$dc /nowarn}
                $icmp = ($w32tm -like "*ICMP*") -replace "ICMP:",""
                
                If($icmp[0] -le "0ms"){$timestatus="Optimal"}
                IF($icmp[0] -gt "300000ms"){$timestatus="Critical. Over 5 mins!"}
                If($icmp[0] -gt "100000ms"){$timestatus="Possible Drift Warning"}
                
                $CPULOAD = invoke-command -computername $DC -scriptblock {Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average }
                $Systems = invoke-command -computername $DC -scriptblock {Get-WMIObject -class Win32_OperatingSystem}
                $Nic=invoke-command -computername $DC -scriptblock {Get-wmiobject -class Win32_NetworkAdapterConfiguration -filter "IPEnabled=True"}
                $ComputerIP = $nic.IPaddress[0] 
				$dnsServers = $nic.dnsserversearchorder 
                              
                                foreach ($system in $Systems) {  
                                   $Bootup = $system.LastBootUpTime  
                                   $LastBootUpTime = WMIDateStringToDate $bootup  
                                   $now = Get-Date
                                   $Uptime = $now - $lastBootUpTime  
                                   $d = $Uptime.Days  
                                   $h = $Uptime.Hours  
                                   $m = $uptime.Minutes  
                                   $ms= $uptime.Milliseconds  
                                                                 }  
			        
						$unreachableServers = foreach ($d in $dnsServers) {
						    try { 
				            if ((-not (Get-Service -Name Dns -ComputerName  $d -ErrorAction SilentlyContinue))  -as [Bool]) {
						        $d
						}
						    } catch {
						         $d
						    }
						    }

							    $adreports=New-Object PSObject -Property @{
							    HasInvalidDNSServerIPs = $($unreachableServers -as [bool])
							    MissingSrvRecords = $($srvLog -as [bool])
							    MissingARecord = $($cflog -as [bool])
							    DnsServerSearchOrder= ($dnsServers -join ([Environment]::Newline))
							    Unreachable_DNS_ServersIP = ($unreachableServers -join ([Environment]::Newline))
                                Computer_IP_Address = $ComputerIP
							    ComputerName = $DC
                                Time_Status = $timestatus
                                Time_Sync = $ICMP
                                Last_Bootup = $LastBootUpTime
                                AverageCPULoad= $CPULOAD.Average
                                Replication_Summary= ( $rep -replace "Beginning data collection for replication summary, this may take awhile:" -join ([Environment]::Newline))}                         
                   
                   $adreports
                   
                                             
              If($srvlog){
              Write-Host "Repairing Missing SRV record on $DC" -ForegroundColor Green
              $Nltest=invoke-command -computername $DC -scriptblock {nltest /dsregdns}
              $Repadmin=invoke-command -computername $DC -scriptblock {Repadmin /syncall}
                         }
                         
              $Nltest
              If($Nltest -like "*ERROR_NO_TRUST_SAM_ACCOUNT*"){
              invoke-command -computername $DC -scriptblock {test-computersecurechannel -repair}

              If($timestatus = "Critical. Over 5 mins!"){
              invoke-command -computername $DC -scriptblock {w32tm /config /update}
              invoke-command -computername $DC -scriptblock {Stop-Service -Name w32time}
              invoke-command -computername $DC -scriptblock {Start-Service -Name w32time}
              invoke-command -ComputerName $DC -ScriptBlock {w32tm /resync}
              invoke-command -computername $DC -scriptblock {Get-Date -Format hh.mm.ss}
              Write-Host "Time Service configured for $DC...." -ForegroundColor Green 
              }
                                                              }   
              
              If($unreachableServers){
              Write-Host "Bad DNS IP:$unreachableServers on $DC" -ForegroundColor Green
  
              $title = "Delete the misconfigured IP"
              $message = "Do you want to delete the misconfigured IP from $DC? "

              $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
                     "Deletes the misconfigured IP from the DNS search order."

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Retains the DNS search order."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

switch ($result)
    {
        0 {"You selected Yes."}
        1 {"You selected No."}
    }
If($result=0){
              invoke-command -computername $DC -scriptblock {netsh interface ipv4 delete dnsservers "local area Connection" $args[0] } -Args $unreachableServers
              invoke-command -computername $DC -scriptblock {netsh interface ipv4 show dnsservers "local area Connection"}
              $Repadmin
              }
                IF($Report){$adreports >> $adreporttxt}
  
  }
                Write-Host "_______________________________________________________________________________________________________" -ForegroundColor Blue
               Write-Host " "
  }
              
If($Domain){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
  ipmo activedirectory
                $DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
} 
}
    
If($filePath){
$Domains=Get-Content $filepath
ForEach($Domain in $Domains){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
$DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
                            }
            }
            }

Open in new window

0
Comment
Question by:siber1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 4
17 Comments
 
LVL 40

Expert Comment

by:footech
ID: 40518316
Just by looking at the code, it appears that it's the contents of $adreports you're interested in.  Currently that is either written out to multiple files or to the console.  So without sending an email for each file, or retrieving the files and sending one email with multiple attachments, you're left with the task of gathering up pretty much all the console output (ignoring the Write-Host commands).  To do so you could replace the final lines with something like this.

$body = @(If($Domain){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
  ipmo activedirectory
                $DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
} 
})
    
$body = @(If($filePath){
$Domains=Get-Content $filepath
ForEach($Domain in $Domains){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
$DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
                            }
            }
})

Send-MailMessage -to you@company.com -from report@company.com -Subject "Report" -Body ($body | Out-String) -SmtpServer mail.company.com

Open in new window


You could process $body in different ways, like with ConvertTo-HTML if you wanted different formatting.
0
 

Author Comment

by:siber1
ID: 40518505
Hi Footech,

thank you for the feedback. I've modified with the code you provided but here is the error I get when running the code:  
Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument
is null or empty. Supply an argument that is not null or empty and then try
the command again.

Open in new window


here is the full code that I am running with your modification. please advise  thx:
########################################
#Get-ADForestHealth V2
#By Winston McMiller
#Synoposis: script leverages Repadmin.exe and DCdiag.exe across the entire forest or domain to help analysis and troubleshooting. 


Param(
  [string]$filePath,
  [string]$Domain,
  [Switch]$Report
    )

$local = $env:Computername + "."+ $env:Userdnsdomain


Function WMIDateStringToDate($Bootup) {  
    [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup)  
} 

Function Get-ForestDNSAnalysis_Local{

                $adreporttxt = "ADREPORT for" + $domain + (Get-Date -Format M.d.yyyy.hh.mm.ss) +".txt"          
                $Dcdiag= dcdiag /test:DNS /v
                $DNSLog= $dcDiag -like "*invalid DNS server*" 
				$SRVLog= $dcDiag -like "*Missing SRV record*"
				$SRVLog2=$dcDiag -like "*Error details: 9003*"
                $CFLOG= $dcDiag -like "*Missing A record at DNS server*"
				$REP=repadmin /replsummary
                $w32tm = w32tm /monitor /computers:$dc /nowarn
                $icmp = ($w32tm -like "*ICMP*") -replace "ICMP:",""
                
                If($icmp -le "0ms"){$timestatus="Optimal"}
                IF($icmp -gt "300000ms"){$timestatus="Critical. Over 5 mins!"}
                If($icmp -gt "100000ms"){$timestatus="Possible Drift Warning"}
                
                $CPULOAD= Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average 
                $Systems = Get-WMIObject -class Win32_OperatingSystem -computer $dc  
                $NIC=Get-wmiobject -class Win32_NetworkAdapterConfiguration -filter "IPEnabled=True"
                $ComputerIP = $nic.IPaddress[0] 
				$dnsServers = $nic.dnsserversearchorder 
                              
                                foreach ($system in $Systems) {  
                                   $Bootup = $system.LastBootUpTime  
                                   $LastBootUpTime = WMIDateStringToDate $bootup  
                                   $now = Get-Date
                                   $Uptime = $now - $lastBootUpTime  
                                                               }                                                              
                                                    
                		$unreachableServers = foreach ($d in $dnsServers) {
						    try { 
				        if ((-not (Get-Service -Name Dns -ComputerName  $d -ErrorAction SilentlyContinue))  -as [Bool]) {
						        $d
						}
						    } catch {
						         $d
						    }
						    }

							    $ADreports=New-Object PSObject -Property @{
							    HasInvalidDNSServerIPs = $($unreachableServers -as [bool])
							    MissingSrvRecords = $($srvLog -as [bool])
							    MissingARecord = $($cflog -as [bool])
							    DnsServerSearchOrder= ($dnsServers -join ([Environment]::Newline))
							    Unreachable_DNS_ServersIP = ($unreachableServers -join ([Environment]::Newline))
                                Computer_IP_Address = $ComputerIP
							    ComputerName = $DC
                                Time_Status = $timestatus
                                Time_Sync = $ICMP
                                Last_Bootup = $LastBootUpTime
                                AverageCPULoad= $CPULOAD.Average
                                Replication_Summary= ( $rep -replace "Beginning data collection for replication summary, this may take awhile:" -join ([Environment]::Newline))}                         
                                
                                $adreports                                
                                             
              If($srvlog){
              Write-Host "Repairing Missing SRV record on $DC" -ForegroundColor Green
              nltest /dsregdns
              $Repadmin=Repadmin /syncall
                         }
                         
              $Nltest
              If($Nltest -like "*ERROR_NO_TRUST_SAM_ACCOUNT*"){
              test-computersecurechannel -repair
                                                              } 
                                                              
              If($timestatus = "Critical. Over 5 mins!"){
              w32tm /config /update
              w32tm /resync
              Stop-Service -Name w32time
              Start-Service -Name w32time
              Get-Date -Format hh.mm.ss
              Write-Host "Time Service configured for $DC...." -ForegroundColor Green 
              }                                                
              
              If($unreachableServers){
              Write-Host "Bad DNS IP:$unreachableServers on $DC" -ForegroundColor Green
  
              $title = "Delete the misconfigured IP"
              $message = "Do you want to delete the misconfigured IP from $DC? "

              $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
                     "Deletes the misconfigured IP from the DNS search order."

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Retains the DNS search order."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

switch ($result)
    {
        0 {"You selected Yes."}
        1 {"You selected No."}
    }
If($result=0){
              netsh interface ipv4 delete dnsservers "local area Connection" $unreachableServers
              netsh interface ipv4 show dnsservers "local area Connection"
              $Repadmin
              }
                
               Write-Host "_______________________________________________________________________________________________________" -ForegroundColor Blue
               Write-Host " "
  }   
             IF($Report){$adreports >> $adreporttxt}  
  }                     

Function Get-ForestDNSAnalysis{
                
                $adreporttxt= "ADREPORT for" + $domain + (Get-Date -Format M.d.yyyy.hh.mm.ss) +".txt"  
                $Dcdiag = invoke-command -computername $DC -scriptblock {dcdiag /test:DNS /v}
                $DNSLog= $dcDiag -like "*invalid DNS server*" 
				$SRVLog= $dcDiag -like "*Missing SRV record*"
				$SRVLog2=$dcDiag -like "*Error details: 9003*"
				$CFLOG= $dcDiag -like "*Missing A record at DNS server*"
				$REP = invoke-command -computername $DC -scriptblock {repadmin /replsummary | where {$_ -ne ""}}
                $w32tm = invoke-command -computername $DC -scriptblock{w32tm /monitor /computers:$dc /nowarn}
                $icmp = ($w32tm -like "*ICMP*") -replace "ICMP:",""
                
                If($icmp[0] -le "0ms"){$timestatus="Optimal"}
                IF($icmp[0] -gt "300000ms"){$timestatus="Critical. Over 5 mins!"}
                If($icmp[0] -gt "100000ms"){$timestatus="Possible Drift Warning"}
                
                $CPULOAD = invoke-command -computername $DC -scriptblock {Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average }
                $Systems = invoke-command -computername $DC -scriptblock {Get-WMIObject -class Win32_OperatingSystem}
                $Nic=invoke-command -computername $DC -scriptblock {Get-wmiobject -class Win32_NetworkAdapterConfiguration -filter "IPEnabled=True"}
                $ComputerIP = $nic.IPaddress[0] 
				$dnsServers = $nic.dnsserversearchorder 
                              
                                foreach ($system in $Systems) {  
                                   $Bootup = $system.LastBootUpTime  
                                   $LastBootUpTime = WMIDateStringToDate $bootup  
                                   $now = Get-Date
                                   $Uptime = $now - $lastBootUpTime  
                                   $d = $Uptime.Days  
                                   $h = $Uptime.Hours  
                                   $m = $uptime.Minutes  
                                   $ms= $uptime.Milliseconds  
                                                                 }  
			        
						$unreachableServers = foreach ($d in $dnsServers) {
						    try { 
				            if ((-not (Get-Service -Name Dns -ComputerName  $d -ErrorAction SilentlyContinue))  -as [Bool]) {
						        $d
						}
						    } catch {
						         $d
						    }
						    }

							    $adreports=New-Object PSObject -Property @{
							    HasInvalidDNSServerIPs = $($unreachableServers -as [bool])
							    MissingSrvRecords = $($srvLog -as [bool])
							    MissingARecord = $($cflog -as [bool])
							    DnsServerSearchOrder= ($dnsServers -join ([Environment]::Newline))
							    Unreachable_DNS_ServersIP = ($unreachableServers -join ([Environment]::Newline))
                                Computer_IP_Address = $ComputerIP
							    ComputerName = $DC
                                Time_Status = $timestatus
                                Time_Sync = $ICMP
                                Last_Bootup = $LastBootUpTime
                                AverageCPULoad= $CPULOAD.Average
                                Replication_Summary= ( $rep -replace "Beginning data collection for replication summary, this may take awhile:" -join ([Environment]::Newline))}                         
                   
                   $adreports
                   
                                             
              If($srvlog){
              Write-Host "Repairing Missing SRV record on $DC" -ForegroundColor Green
              $Nltest=invoke-command -computername $DC -scriptblock {nltest /dsregdns}
              $Repadmin=invoke-command -computername $DC -scriptblock {Repadmin /syncall}
                         }
                         
              $Nltest
              If($Nltest -like "*ERROR_NO_TRUST_SAM_ACCOUNT*"){
              invoke-command -computername $DC -scriptblock {test-computersecurechannel -repair}

              If($timestatus = "Critical. Over 5 mins!"){
              invoke-command -computername $DC -scriptblock {w32tm /config /update}
              invoke-command -computername $DC -scriptblock {Stop-Service -Name w32time}
              invoke-command -computername $DC -scriptblock {Start-Service -Name w32time}
              invoke-command -ComputerName $DC -ScriptBlock {w32tm /resync}
              invoke-command -computername $DC -scriptblock {Get-Date -Format hh.mm.ss}
              Write-Host "Time Service configured for $DC...." -ForegroundColor Green 
              }
                                                              }   
              
              If($unreachableServers){
              Write-Host "Bad DNS IP:$unreachableServers on $DC" -ForegroundColor Green
  
              $title = "Delete the misconfigured IP"
              $message = "Do you want to delete the misconfigured IP from $DC? "

              $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
                     "Deletes the misconfigured IP from the DNS search order."

$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Retains the DNS search order."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

switch ($result)
    {
        0 {"You selected Yes."}
        1 {"You selected No."}
    }
If($result=0){
              invoke-command -computername $DC -scriptblock {netsh interface ipv4 delete dnsservers "local area Connection" $args[0] } -Args $unreachableServers
              invoke-command -computername $DC -scriptblock {netsh interface ipv4 show dnsservers "local area Connection"}
              $Repadmin
              }
                IF($Report){$adreports >> $adreporttxt}
  
  }
                Write-Host "_______________________________________________________________________________________________________" -ForegroundColor Blue
               Write-Host " "
  }
              
$body = @(If($Domain){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
  ipmo activedirectory
                $DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
} 
})
    
$body = @(If($filePath){
$Domains=Get-Content $filepath
ForEach($Domain in $Domains){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
$DCS=(get-addomain $domain).ReplicaDirectoryServers
                Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
                            }
            }
})

Send-MailMessage -to user@mydomain.com -from report@mydomain.com -Subject "Active Directory Report" -Body ($body | Out-String) -SmtpServer smtp.mydomain.com

Open in new window

0
 

Author Comment

by:siber1
ID: 40519233
Hi Footech, any advice on the error I am receiving per my last post?

thx
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 40

Accepted Solution

by:
footech earned 250 total points
ID: 40519621
It took me a while... I just wasn't seeing where the problem was.  The problem was $body was collecting the output on line 241, but was then being overwritten with blank content on line 251.  We need to define $body within the If scriptblocks so that doesn't happen.
Make the following change.
If($Domain){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
  ipmo activedirectory
                $DCS=(get-addomain $domain).ReplicaDirectoryServers
                $body = Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
} 
}
    
If($filePath){
$Domains=Get-Content $filepath
ForEach($Domain in $Domains){
Write-Host "Enumerating $Domain Domain...." -ForegroundColor Green
$DCS=(get-addomain $domain).ReplicaDirectoryServers
                $body = Foreach($DC in $DCS){
                If($local -eq $DC){Get-ForestDNSAnalysis_Local}
                If($local -ne $DC){Get-ForestDNSAnalysis}
                            }
            }
            }

Send-MailMessage -to user@mydomain.com -from report@mydomain.com -Subject "Active Directory Report" -Body ($body | Out-String) -SmtpServer smtp.mydomain.com

Open in new window

0
 

Author Comment

by:siber1
ID: 40519652
hi Footech, that fixed the auto-email component. thanks much.   is there anyway to fix the format of the report? its all over the place, here is how it lines up in email:

DnsServerSearchOrder      : 172..x.x.x
                            172.x.x.x
Time_Status               : Optimal
AverageCPULoad            : 4.5
MissingARecord            : False
HasInvalidDNSServerIPs    : False
Replication_Summary       : Replication Summary Start Time: 2014-12-27 10:30:13
                           
                              ...............
                            Source DSA          largest delta    fails/total %%   error
                             dom-AD-01                 30m:46s    0 /  10    0  
                             dom-AD-02                 43m:47s    0 /   5    0  
                             domCADC1              06h:28m:44s   10 /  10  100  (1722) The RPC server is unavailable.
                             domMADC1                  35m:24s    0 /  20    0  
                             domMADC2                  35m:36s    0 /  15    0  
                             domUKDC                   05m:22s    0 /   5    0  
                             domAZUREDC01           32m:49s    0 /  10    0  
                             domOPSMADC01              35m:36s    0 /  20    0  
                             WINOPSMADC02        (unknown)        0 /  15    0  
                            Experienced the following operational errors trying to retrieve replication information:
                                      58 - domCADC1.mydomain.COM
Time_Sync                 : {     0ms }
Computer_IP_Address       : 172.x.x.x
MissingSrvRecords         : False
ComputerName              : domCADC1.mydomain.COM
Last_Bootup               : 2/14/2014 12:03:45 PM
Unreachable_DNS_ServersIP :

is there anyway to make it line up like this:

DnsServerSearchOrder      : 172..x.x.x
                            172.x.x.x
Time_Status               : Optimal
AverageCPULoad            : 4.5
MissingARecord            : False
HasInvalidDNSServerIPs    : False
Replication_Summary       : Replication Summary Start Time: 2014-12-27 10:30:13
                            
                              ...............
                            Source DSA          largest delta    fails/total %%   error
                             dom-AD-01                 30m:46s    0 /  10    0  
                             dom-AD-02                 43m:47s    0 /   5    0  
                             domCADC1              06h:28m:44s   10 /  10  100  (1722) The RPC server is unavailable.
                             domMADC1                  35m:24s    0 /  20    0  
                             domMADC2                  35m:36s    0 /  15    0  
                             domUKDC                   05m:22s    0 /   5    0  
                             domAZUREDC01           32m:49s    0 /  10    0  
                             domOPSMADC01              35m:36s    0 /  20    0  
                             WINOPSMADC02        (unknown)        0 /  15    0  
                            Experienced the following operational errors trying to retrieve replication information:
                                      58 - domCADC1.mydomain.COM
Time_Sync                 : {     0ms }
Computer_IP_Address       : 172.x.x.x
MissingSrvRecords         : False
ComputerName              : domCADC1.mydomain.COM
Last_Bootup               : 2/14/2014 12:03:45 PM
Unreachable_DNS_ServersIP : 

Open in new window

0
 
LVL 40

Expert Comment

by:footech
ID: 40520034
You have to configure your email client to display plain-text emails with a fixed-width font.  Your PS console output would look the same way if you used a variable width font for it.

The other option is to process $body so that it is HTML.
0
 

Author Comment

by:siber1
ID: 40520037
thanks Footech, how can I leverage option 2 - "process $body so that it is HTML"?
0
 

Author Comment

by:siber1
ID: 40520471
hi Footech, can you provide instructions as to how I can leverage that second option you proposed to "process $body so that it is HTML"?

many thanks.

S.
0
 
LVL 40

Expert Comment

by:footech
ID: 40520531
Asking multiple times doesn't help.  :)
I haven't had much time the last few days to respond.

Converting to HTML brings it's own problems with formatting.  Changing your email client setting is the easier fix.

As in some of your other recent questions, you can utilize ConvertTo-HTML to convert objects to HTML.  But you'll see limitations when doing so because of how HTML is displayed.  For example, a newline doesn't mean anything in HTML, so to display a new line in HTML you have to use <br>, but if you send a string property that contains <br> to ConvertTo-HTML that HTML code is not recognized as such but is converted so that it will display as "<br>" and not a new line.
You can see the issues for yourself by running the following.
Send-MailMessage -to user@mydomain.com -from report@mydomain.com -Subject "Active Directory Report" -Body ($body | ConvertTo-Html -As List | Out-String) -BodyAsHtml -SmtpServer smtp.mydomain.com

Open in new window

0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40520630
I agree - formatting that list as HTML for better output is complex, because the source is just text with some formatting applied thought to be used with a monotype font.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40520647
Another way: embed the text output into <pre>....</pre> tags, to "preserve formatting", as far as possible.
0
 

Author Comment

by:siber1
ID: 40520733
thanks for the input Qlemo & Footech, I think i'll approach it a different way and send as a txt attachment. if possible, can you provide a way to modify the code so that it sends the results as a .txt attachment rather than embed the results in an email?

S.
0
 
LVL 70

Assisted Solution

by:Qlemo
Qlemo earned 250 total points
ID: 40520935
$body | out-file c:\temp\report.txt

Send-MailMessage -to user@mydomain.com -from report@mydomain.com -Subject "Active Directory Report" -attachments c:\temp\report.txt -SmtpServer smtp.mydomain.com

Open in new window

0
 

Author Comment

by:siber1
ID: 40520971
hi Qlemo,
it looks like the $body variable is empty.

I've added that to the bottom of the script, and it emails the .txt file as an attachment, however the file is empty.

thx - S.
0
 
LVL 70

Expert Comment

by:Qlemo
ID: 40520980
I've based that on the change shown in http:#a40519621 to fill the $body variable.
0
 

Author Closing Comment

by:siber1
ID: 40521072
thanks Footech / Qlemo, I split the points, really appreciate the guidance on this. Footech my apologies for pinging you a second time on the same question.

happy holidays.

S.
0
 
LVL 40

Expert Comment

by:footech
ID: 40521130
No need to apologize.  :)

Happy holidays!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
Previously, on our Nano Server Deployment series, we've created a new nano server image and deployed it on a physical server in part 2. Now we will go through configuration.
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
The video tutorial explains the basics of the Exchange server Database Availability groups. The components of this video include: 1. Automatic Failover 2. Failover Clustering 3. Active Manager

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question