Skip to main content

Testing if a Resource is online

I was sitting in the USO at the San Jose airport a few months ago after teaching a class when I got a call from a friend who had an issue.  Apparently, his company’s email server went down.  It had been down for about 24 hours.  Of course the first person to take note of this was the big boss her self.  He asked me if PowerShell could tell him when a serve is down.

This reminded me of a script that I ran years ago that would test connectivity to all of my resources (servers, printers, routers, etc.) and then dropped me an email to let me know if I had work to do.  This email would say something like “Have a nice day” if nothing was wrong in the subject line.  It would say something else if there was a problem and then I would have to open it.

I spent about an hour building a test environment and rebuilt that script in PowerShell for my friend.  He was very happy to receive it. For this years SMB Nation Emerging Technology Tour, I decided build a simplified version of it.  I also set it up as a scheduled job to make life a bit easier on him.  Here is the simplified version:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Function Test-Network

{

Param ($ComputerName)

   

    ForEach ($Name in $ComputerName)

    {

        $Hash = @{'Quiet' = $True;

                  'Count' = 1;

                  'ComputerName' = $Name}

        If (!(Test-Connection @Hash))

        {

            $MailHash = @{'To' = "Administrator@TechTour.com";

                          'From' = "LittleGreenMen@Mars.Planet";

                          'Subject' = "Sever $Name is offline";

                          'Body' = "Have a nice day";

                          'SMTPServer' = "Tech-ex1"}

            Send-MailMessage @MailHash

        }

    }

}

Test-Network -ComputerName Tech-EX1, Tech-EX11

The first thing to notice is that this is a function.  Ok, I like to make things functions.  Line 21 is where you place the names or IP addresses of all the resources that you want to test a connection to in a comma separated list.  You may also want to adjust the following values in the hash table in lines 12 – 16.  To is the email address to send to.  Notice that this code only supports sending to one email address.  From:  I doubt that you would want to receive an email form Mars.  You may want to give this a name like ResourceConnectivityTest@YourDomain.com.  Otherwise your Exchange server may send the message to the Phantom Zone.  Also the SMTPServer should be the name of your SMTP Server.

Once this is done, save this script to a server that will always be on.  No point on putting this on your laptop.  You want something that will have persistent connectivity to your network.  We are now going to set this script up as a scheduled job.

First we are going to create a DateTime object that species the time that this code will run.  Let’s say that we want this report to run at 7:45 AM everyday.  That way it is in our inbox when we get to work at 8.

PS C:\psworks> Get-Date -hour 7 -Minute 45

 

Thursday, February 6, 2014 7:45:06 AM

 

The time right now is actually 4:49 PM.  The date does not matter, we just need to save this DateTime object to a variable.

PS C:\psworks> $Time = Get-Date -hour 7 -Minute 45

 

We will use this variable with the New-JobTrigger cmdlet.  This will determine what triggers this scheduled task.  The New-JobTrigger cmdlet also sets the frequency that the task will run.  The following options are available to schedule the task to repeat.

 

-AtLogOn Starts when the user logs on.
-AtStartUp Starts when Windows boots.
-Daily Every day at the specified time.
-DaysOfWeek This allows you to select the day of the week that the task runs.  You can provide a comma separated list of either strings or integers to represent the days of the week.
String Integer
“Sunday” 0
“Monday” 1
“Tuesday” 2
“Wednesday” 3
“Thursday” 4
“Friday” 5
“Saturday” 6
-Once Only runs once.
-Weekly Runs once a week
-WeeksInterval Used in conjunction with –Weekly, this integer specifies the number of weeks to skip.

For this task, we want it to run daily.  We will save the trigger object in the variable $Trigger.

$Trigger = New-JobTrigger -At $Time -Daily

 

Now we are ready to register the job.  Remember that the script and the scheduled job needs to be on a server that is always on and connected to the network. 

PS C:\psworks> Register-ScheduledJob -Name "Server Check" -FilePath "C:\PS\ServerTest.ps1" -Trigger $Trigger -Credential "TechTour\Administrator"

 

Id         Name            JobTriggers     Command                            

--         ----            -----------     -------                            

1          Server Check    1               C:\PS\ServerTest.ps1 

 

You will be prompted for the credentials of the user or service account that will be running this script.  In this example, I used a user account but in practice, I would assign a service account to avoid problems with password changes and also with security on your Exchange Server so you are not permitting it to send emails from outside domain.

image

Open the Task Scheduler and take a look at your scheduled task.  it is located at: Task Scheduler Library / Microsoft / Windows / PowerShell / Scheduled Jobs

image

 

You are all done.  Just check your email in the morning.

Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.