Solved

Combine two scripts and email one output

Posted on 2014-02-07
6
537 Views
Last Modified: 2014-02-14
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
Comment
Question by:hlaten
  • 3
  • 3
6 Comments
 
LVL 40

Accepted Solution

by:
Subsun earned 500 total points
ID: 39843120
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
 

Author Comment

by:hlaten
ID: 39843233
This is not what I thought I woud get, but it actually makes it simple and does the job. Excellent and thank you.
0
 

Author Closing Comment

by:hlaten
ID: 39843235
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
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
LVL 40

Expert Comment

by:Subsun
ID: 39843246
It is possible to modify the code and add the details which you require..Report format also can be changed..
0
 

Author Comment

by:hlaten
ID: 39848587
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
 
LVL 40

Expert Comment

by:Subsun
ID: 39859087
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone 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

Set OWA language and time zone in Exchange for individuals, all users or per database.
The recent Microsoft changes on update philosophy for Windows pre-10 and their impact on existing WSUS implementations.
This tutorial will show how to push an installation of Backup Exec to an additional server in both 2012 and 2014 versions of the software. Click on the Backup Exec button in the upper left corner. From here, select Installation and Licensing, then I…
This tutorial will walk an individual through configuring a drive on a Windows Server 2008 to perform shadow copies in order to quickly recover deleted files and folders. Click on Start and then select Computer to view the available drives on the se…

840 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