?
Solved

Combine two scripts and email one output

Posted on 2014-02-11
2
Medium Priority
?
229 Views
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:


<#
      .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 #######################
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
Answers
 
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
}
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
Select allOpen in new window
500 points

EXCELLENT
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
0
Comment
Question by:hlaten
[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
  • 2
2 Comments
 

Accepted Solution

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

Author Closing Comment

by:hlaten
ID: 39994275
Thank you for the solution.
0

Featured Post

Bringing Advanced Authentication to the SMB Market

WatchGuard announces the acquisition of advanced authentication provider, Datablink, with one mission – to bring secure authentication to SMB, mid-market, and distributed enterprises with a cloud-based solution, ideal for resale via their established channel & MSSP community.

Question has a verified solution.

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

Background Information Recently I have fixed file server permission issues for one of my client. The client has 1800 users and one Windows Server 2008 R2 domain joined file server with 12 TB of data, 250+ shared folders and the folder structure i…
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
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…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Suggested Courses

770 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