Combine two scripts and email one output

Posted on 2014-02-11
Medium Priority
Last Modified: 2014-04-11
I have a few domains that are not connected to the internet, can you just have the output go to an html file. Also is there a way to include timestamps for password and lastlogon converted into readable format? For both email output and the html file.

Combine two scripts and email one output
Asked by: hlatenSolved by: Subsun Can someone help with combining two scripts together? The first script is a script that collects stale computers that have not logged in within a set number of days and then emails the output to an individual or team. The second script pings computers and states whether they are alive and pinging or dead and not pinging. I would like to be able to ping the computers that are listed in the output of the first scripts and have a column in the emailed report that is the output of the pinged script.

Find Stale Computer script:

      Create HTML e-mail report of stale Computers based on input parameters

      Find all Computers in a given OU or domain which have not authenticated to the domain in a given number of days or have never authenticated to domain. Script uses both the lastLogonTimestamp and pwdLastSet attributes of the user object to determine when the user last authenticated. E-mail settings are configurable within script.
      NOTE: This is not real-time data!

      Active Directory Organizational Unit to restrict search. Needs to be in LDAP syntax, (ex. "OU=Department,DC=domain,DC=com"). Entire domain can be searched using "DC=domain,DC=com" syntax.

      .PARAMETER NumberOfDays
      Script will return Computer accounts that have not authenticated since this date. DateTime object. Defaults to 90 days ago.
      .PARAMETER LogFilePath
      Path to directory where log file will be placed. Defaults to "C:\Scripts\Logs\StaleUsers"

      .\Generate-StaleComputerReport.ps1 -OU "DC=Domain,DC=COM"
      Searches entire domain for computers thathave not authenticated within the last 90 days
      .\Generate-StaleComputerReport-rc.ps1 -OU "DC=www,DC=yahoo,DC=com" -NumberOfDays (Get-Date).AddDays(-120) -LogfilePath "C:\temp"
      Searches entire domain for Computers that have not authenticated within the last 120 days. It saves the log file in C:\temp

            NAME:  Generate-StaleUsersReport.ps1
            AUTHOR: Charles Downing
            LASTEDIT: 02/18/2013

      [Parameter(position=1)][string]$OU = "DC=www,DC=yahoo,DC=com",
      [DateTime]$NumberOfDays = (Get-Date).AddDays(-90),
      [string]$LogfilePath = "C:\Scripts\Logs\StaleUsers"

$NumberOfDaysTS = $NumberOfDays.ToFileTime()
$Logfile = "{0}\{1}_StaleUsers.log" -f $LogfilePath, (Get-Date -Format yyyyMMdd_hhmmsstt)
$ScriptName = [system.io.path]::GetFilenameWithoutExtension($MyInvocation.MyCommand.Path)
$date = Get-Date -Format d
$MAIL_SERVER = "my.dots.com"
$FROM_ADDR = "you@dotscom"
$TO_ADDR = "you@dotscom"
$EMAIL_SUBJECT = "Stale computers in DC=www.yahoo,DC=com AD - $date"
$STYLE = "
                  BODY {
                        font-family: Verdana, Arial, Helvetica, sans-serif;
                        font-size: 12px;
                  TABLE {
                        border-width: 1px;
                        border-style: solid;
                        border-color: black;
                        border-collapse: collapse;
                  TH {
                        border-width: 1px;
                        padding: 5px;
                        border-style: solid;
                        border-color: black;
                        background-color: #005DAB;
                        color: #FFFFFF
                  TD {
                        border-width: 1px;
                        padding: 5px;
                        border-style: solid;
                        border-color: black;
                        background-color: #D2E6F4
                  .sizeRed {
                        background-color: Red
                  .sizeYellow {
                        background-color: Yellow
                  .summaryHeading {
                        font-style: italic;
                        font-weight: bold;
                        background-color: #A0A0A0;
                  .summaryLine {
                        background-color: #A0A0A0;
                        text-align: right;

# adapted from http://stackoverflow.com/questions/7834656/create-log-file-in-powershell
Function LogWrite
         Param (
            [Parameter(position=1)][int]$severity = 0
      switch ($severity)
                  $severityStr = "INFO"
                  $severityStr = "WARNING"
                  $severityStr = "ERROR"
                  $severityStr = "CRITICAL"
      $logEntry = "{0} - {1}: {2}" -f (Get-Date -Format u), $severityStr, $logstring

      Add-content $Logfile -value $logEntry

Function SendHTMLEmail
      LogWrite "Creating e-mail" 0
      $staleUsers_html = $staleUsers | Sort-Object LastLogonTime | ConvertTo-Html -Fragment
      $htmlBody = "
                  The following Computers last authenticated to the domain on or before $(Get-Date -Date $NumberOfDays -Format d)`:<BR>
      $htmlBody += "
                  <BR><small><small>Report located on server01: $ScriptName</small></small>

      LogWrite "Sending e-mail to $TO_ADDR from $FROM_ADDR at $(Get-Date -format g)" 0
            Send-MailMessage -From $FROM_ADDR -To $TO_ADDR -Subject $EMAIL_SUBJECT -Body $htmlBody -SmtpServer $MAIL_SERVER -BodyAsHtml -ErrorAction SilentlyContinue
                  throw $error[0].Exception
      catch [System.Exception]
            LogWrite "E-mail not sent successfully: $_" 3
            Write-Host "Exception thrown: $_" -ForegroundColor Red

if(!(Test-Path -Path $LogfilePath -PathType Container))
      New-Item -ItemType Directory -Path $LogfilePath

LogWrite "----- Processing started by $env:username -----" 0

$LDAPOU = "LDAP://{0}" -f $OU
            LogWrite "Generating list of enabled Computers where lastLogonTimestamp and pwdLastSet attributes are older than $NumberOfDays" 0
            $staleUsers = Get-ADcomputer `
                  -SearchBase $OU `
                  -filter {(lastLogonTimestamp -notlike "*" -OR lastLogonTimestamp -le $NumberOfDaysTS) -AND (pwdLastSet -le $NumberOfDaysTS) -AND (Enabled -eq $True)} `
                  -Properties lastLogonTimestamp, pwdLastSet |
                  Select-Object `
                        Name, `
                        DNSHostName, `
                        @{Expression={if($_.lastLogonTimestamp -ne $null) {[datetime]::FromFileTime($_.lastLogonTimestamp)}};Label="LastLogonTime"},`
                        @{Expression={if(($_.pwdLastSet -ne $null) -and ($_.pwdLastSet -ne 0)) {[datetime]::FromFileTime($_.pwdLastSet)}};Label="PwdLastSetTime"}
            LogWrite "List generated" 0
      catch [System.Exception]
            LogWrite $_.Exception.Message 3
            Write-Host "Exception thrown: $_" -ForegroundColor Red
      LogWrite "OU does not exist: $LDAPOU" 3
      Write-Host "OU does not exist: $LDAPOU" -ForegroundColor Red

if($staleUsers -ne $null)
      SendHTMLEmail $staleUsers
LogWrite "----- Processing complete -----" 0

Ping Computers script:

#| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = |  
#|: | Author:  Aman Dhally                                        | :|          
#| :| Email:   amandhally@gmail.com
#|: | Purpose: Ping Multiple Servers / Computers    
#|: |                    Date: 15-Nov-2011        
#| :|       /^(o.o)^\           Version: 1                                              |: |
#| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = |

#### Provide the computer name in $computername variable

$ServerName = "Dc-2","LocalHost","Server-2","Not-Exists", "Fake-computer", "Dc-1"

##### Script Starts Here ######

foreach ($Server in $ServerName) {

            if (test-Connection -ComputerName $Server -Count 2 -Quiet ) {
                  write-Host "$Server is alive and Pinging " -ForegroundColor Green
                              } else
                              { Write-Warning "$Server seems dead not pinging"

########## end of script #######################
Asked On:
2014-02-07 at 15:51:03ID28359486Tags:active directory, powershell, ping, stale computersTopics:Powershell,Windows Server 2008,Server ApplicationsParticipating Experts:1Points:500Comments:5¿Request Attention
Accepted Solution
by: SubsunPosted on 2014-02-07 at 16:34:04ID: 39843120
 Rank: Ace
Subsun Member Since: 05/14/2009 1653 Solution(s) 2 Article(s) I didn't get time to go through the code you posted but the following code should give you the inactive computer account details with ping status. If you want to add any other attributes to report then let me know..

$Computers =  Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 90 | % {
      If (Test-Connection $_.Name -Quiet -Count 2){
      $_ | Select Name,@{N="Ping Status";E={"UP"}}
      }Else {
      $_ | Select Name,@{N="Ping Status";E={"Down"}}

$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:Gray}"
$a = $a + "TD{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:White}"
$a = $a + "</style>"

If ($Computers -ne $null) {
Send-MailMessage -From From@domain.com -To To@domain.com -Subject "Inactive Computer Report" -BodyAsHtml ($Computers | ConvertTo-HTML -head $a | Out-String) -SmtpServer smtp.domain.com
Select allOpen in new window
500 points

Save to Personal Knowledgebase
Your Comment
by: hlatenPosted on 2014-02-07 at 17:12:27ID: 39843233
hlaten Member Since: 01/22/2014 This is not what I thought I woud get, but it actually makes it simple and does the job. Excellent and thank you.  
Your Comment
by: hlatenPosted on 2014-02-07 at 17:14:03ID: 39843235
hlaten Member Since: 01/22/2014 This is not what I thought it would look like. ut this does the job and keeps it simple at the same tim. Excellent solution anthank you subsun.  
Expert Comment
by: SubsunPosted on 2014-02-07 at 17:15:46ID: 39843246
 Rank: Ace
Subsun Member Since: 05/14/2009 1653 Solution(s) 2 Article(s) It is possible to modify the code and add the details which you require..Report format also can be changed..  
Your Comment
by: hlatenPosted on 2014-02-10 at 16:37:37ID: 39848587I have a few domains that are not connected to the internet, can you just have the output go to an html file. Also is there a way to include timestamps for password and lastlogon converted into readable format?
hlaten Member Since: 01/22/2014
Question by:hlaten
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
  • 2

Accepted Solution

hlaten earned 0 total points
ID: 39994264
Trying to close, already submitted overall satisfaction and grade.

Author Closing Comment

ID: 39994275
Thank you for the solution.

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

Issue: One Windows 2008 R2 64bit server on the network unable to connect to a buffalo Device (Linkstation) with firmware version 1.56. There are a total of four servers on the network this being one of them. Troubleshooting Steps: Connect via h…
The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…
With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…

649 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