Harrison Aten
asked on
Combine two scripts and email one output
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,D C=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\StaleUser s"
.EXAMPLE
.\Generate-StaleComputerRe port.ps1 -OU "DC=Domain,DC=COM"
Searches entire domain for computers thathave not authenticated within the last 90 days
.EXAMPLE
.\Generate-StaleComputerRe port-rc.ps 1 -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)][st ring]$OU = "DC=www,DC=yahoo,DC=com",
[DateTime]$NumberOfDays = (Get-Date).AddDays(-90),
[string]$LogfilePath = "C:\Scripts\Logs\StaleUser s"
)
$NumberOfDaysTS = $NumberOfDays.ToFileTime()
$Logfile = "{0}\{1}_StaleUsers.log" -f $LogfilePath, (Get-Date -Format yyyyMMdd_hhmmsstt)
$ScriptName = [system.io.path]::GetFilen ameWithout Extension( $MyInvocat ion.MyComm and.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)][st ring]$logs tring,
[Parameter(position=1)][in t]$severit y = 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($_.lastLo gonTimesta mp -ne $null) {[datetime]::FromFileTime( $_.lastLog onTimestam p)}};Label ="LastLogo nTime"},`
@{Expression={if(($_.pwdLa stSet -ne $null) -and ($_.pwdLastSet -ne 0)) {[datetime]::FromFileTime( $_.pwdLast Set)}};Lab el="PwdLas tSetTime"}
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-E xists", "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:act ive directory, powershell, ping, stale computersTopics:Powershell ,Windows Server 2008,Server ApplicationsParticipating Experts:1Points:500Comment s:5¿Reques t 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:whi te;}"
$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:Gra y}"
$a = $a + "TD{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:Whi te}"
$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
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,D
.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\StaleUser
.EXAMPLE
.\Generate-StaleComputerRe
Searches entire domain for computers thathave not authenticated within the last 90 days
.EXAMPLE
.\Generate-StaleComputerRe
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.
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)][st
[DateTime]$NumberOfDays = (Get-Date).AddDays(-90),
[string]$LogfilePath = "C:\Scripts\Logs\StaleUser
)
$NumberOfDaysTS = $NumberOfDays.ToFileTime()
$Logfile = "{0}\{1}_StaleUsers.log" -f $LogfilePath, (Get-Date -Format yyyyMMdd_hhmmsstt)
$ScriptName = [system.io.path]::GetFilen
$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)][st
[Parameter(position=1)][in
)
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($_.lastLo
@{Expression={if(($_.pwdLa
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
##### 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:act
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:whi
$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:Gra
$a = $a + "TD{border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:Whi
$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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER