• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 201
  • Last Modified:

need assistance with a technet script

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
siber1
Asked:
siber1
  • 8
  • 5
  • 4
2 Solutions
 
footechCommented:
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
 
siber1Author Commented:
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
 
siber1Author Commented:
Hi Footech, any advice on the error I am receiving per my last post?

thx
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
footechCommented:
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
 
siber1Author Commented:
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
 
footechCommented:
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
 
siber1Author Commented:
thanks Footech, how can I leverage option 2 - "process $body so that it is HTML"?
0
 
siber1Author Commented:
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
 
footechCommented:
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
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
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
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Another way: embed the text output into <pre>....</pre> tags, to "preserve formatting", as far as possible.
0
 
siber1Author Commented:
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
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
$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
 
siber1Author Commented:
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
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
I've based that on the change shown in http:#a40519621 to fill the $body variable.
0
 
siber1Author Commented:
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
 
footechCommented:
No need to apologize.  :)

Happy holidays!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Building an Effective Phishing Protection Program

Join Director of Product Management Todd OBoyle on April 26th as he covers the key elements of a phishing protection program. Whether you’re an old hat at phishing education or considering starting a program -- we'll discuss critical components that should be in any program.

  • 8
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now