Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 558
  • Last Modified:

Combine two scripts and email one output

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:


<#
      .SYNOPSIS
      Create HTML e-mail report of stale Computers based on input parameters

      .DESCRIPTION
      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!

      .PARAMETER OU
      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"

      .EXAMPLE
      .\Generate-StaleComputerReport.ps1 -OU "DC=Domain,DC=COM"
      
      Searches entire domain for computers thathave not authenticated within the last 90 days
      
      .EXAMPLE
      .\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

      .NOTES
            NAME:  Generate-StaleUsersReport.ps1
            AUTHOR: Charles Downing
            LASTEDIT: 02/18/2013
            KEYWORDS:
      .LINK
      http://blogs.technet.com/b/askds/archive/2009/04/15/the-lastlogontimestamp-attribute-what-it-was-designed-for-and-how-it-works.aspx
#>

Param(
      [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 = "
            <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;
                  }
            </STYLE>"

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

      Add-content $Logfile -value $logEntry
}

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

      LogWrite "Sending e-mail to $TO_ADDR from $FROM_ADDR at $(Get-Date -format g)" 0
      try
      {
            Send-MailMessage -From $FROM_ADDR -To $TO_ADDR -Subject $EMAIL_SUBJECT -Body $htmlBody -SmtpServer $MAIL_SERVER -BodyAsHtml -ErrorAction SilentlyContinue
            if(!$?)
            {
                  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
if([adsi]::Exists($LDAPOU))
{
      try
      {
            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
      }
}
else
{
      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 #######################
0
hlaten
Asked:
hlaten
  • 3
  • 3
1 Solution
 
SubsunCommented:
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
}

Open in new window

0
 
hlatenAuthor Commented:
This is not what I thought I woud get, but it actually makes it simple and does the job. Excellent and thank you.
0
 
hlatenAuthor Commented:
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.
0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
SubsunCommented:
It is possible to modify the code and add the details which you require..Report format also can be changed..
0
 
hlatenAuthor Commented:
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?
0
 
SubsunCommented:
Following code will export the report to c:\report.htm, let me know if you have any questions..

$Computers =  Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 90 | % {
	If (Test-Connection $_.Name -Quiet -Count 2){
	$_ | Select Name,LastLogonDate,@{N="Ping Status";E={"UP"}}
	}Else {
	$_ | Select Name,LastLogonDate,@{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) {
$Computers | ConvertTo-HTML -head $a | Out-file c:\report.htm
}

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now