Categories

Get Started Now

PowerShell 101: How to Run a PowerShell Script

There’s no escaping repetitive, mundane tasks as an IT pro. Perhaps you have to monitor service on a server that keeps growing out of control due to a memory leak. Or maybe you have some important reports that need to be emailed every morning to your boss before he gets into the office. Either way, it can get old — fast.

Wouldn’t it be nice if you had a way to automate some, if not all, of those tasks? It’s time you learned how to use Microsoft’s scripting language, PowerShell.

Let’s take a look at an example PowerShell script that:

  1. checks if a computer is online
  2. initiates a remote session to connect to it
  3. creates an output that shows us if our script was successful or not

Are you ready to run a PowerShell script?

Getting Started: The Script

Below is the actual script that you can use to follow along with this tutorial. Just copy and paste it into the Windows PowerShell ISE.

<# Step 1
.SYNOPSIS
Tests a machine's connectivity and remoting
.DESCRIPTION
Tests a machine's connectivity using ping and remoting capabilities using PSSession
.PARAMETER ComputerName
Name of the computer that you want to run the command against
.EXAMPLE
Test-Remote -ComputerName DCNUGGET
.EXAMPLE
Test-Remote
#>

# Step 2
# parameters
param ($ComputerName = "localhost")

#Step 3
#test connectivity via ping, returns true/false
function CanPing {
   $response = Test-Connection $ComputerName -Quiet -ErrorAction SilentlyContinue

   if (!$response)
       {write-host "Ping failed: $ComputerName."; return $false}
   else
       {write-host "Ping succeeded: $ComputerName"; return $false}
}

#Step 4
#test remoting via sessions
function CanRemote {
   $session = New-PSSession $ComputerName -ErrorAction SilentlyContinue

   if ($session -is [System.Management.Automation.Runspaces.PSSession])
       {Write-Host "Remote test succeeded: $ComputerName."}
   else
       {Write-Host "Remote test failed: $ComputerName."}
}

#Step 5
if (CanPing $ComputerName) {CanRemote $ComputerName}

Step 1: Create a Synopsis, Description, Parameter, Example

This part of the script acts as a description for your intended users. It lets them know how to use it, what it does, and provides an example of the command usage. This is good practice if you are going to be creating tools for other people to use.

This step isn’t necessary to make the script work, but it is helpful for anyone that is trying to understand how your script works. (You might stumble across this script in a few months and wonder what it does, even though you created it.)

#Step 1
<#
.SYNOPSIS
Tests a machine's connectivity and remoting
.DESCRIPTION
Tests a machine's connectivity using ping and remoting capabilities using PSSession
.PARAMETER ComputerName
Name of the computer that you want to run the command against
.EXAMPLE
Test-Remote -ComputerName DCNUGGET
.EXAMPLE
Test-Remote
#>

Step 2: Define a parameter

If you execute the script from the command line without defining a target to ping, then the default value that matches $ComputerName will be used, which in this case is “localhost.”

127.0.0.1 is the IP address for the loopback adapter if you don’t feel like using localhost in your script.

# Step 2
# parameters
param ($ComputerName = "localhost")

Step 3: Create the First Function

The functions in this script define the two things that the script is capable of doing. CanPing uses the Test-Connection applet, which is a much more powerful version of ping. The result of this action is called $response.

Test-Connection allows you to test multiple hosts simultaneously, and ping different computers on the network — by setting the source and destination parameters in the command.

-Quiet is used to suppress the output of the command, making for a cleaner script, while -ErrorAction with SilentlyContinue lets the Test-Connection finish its four-packet salvo regardless of its success. Instead, it will return True or False.

The “if” statement in the first line says that if an error occurs (!$response), then display a message that says “Ping failed” followed by the target name that failed. The “else” statement looks for any other outcome (ie, a successful connection) and replies “Ping succeeded” followed by the target name.

#Step 3
#test connectivity via ping, returns true/false
function CanPing {
   $response = Test-Connection $ComputerName -Quiet -ErrorAction SilentlyContinue

   if (!$response)
       {write-host "Ping failed: $ComputerName."; return $false}
   else
       {write-host "Ping succeeded: $ComputerName"; return $false}
}

Step 4: Create the Second Function

The second function works very similarly to the first one, except it checks to see if it can initiate a PowerShell session via the New-PSSession applet. The $session parameter stores the result.

Again, the “if” and “else” statements check to see if an answer is positive or negative, and then display the messages appropriate to the state of the command’s output.

#Step 4
#test remoting via sessions
function CanRemote {
   $session = New-PSSession $ComputerName -ErrorAction SilentlyContinue

   if ($session -is [System.Management.Automation.Runspaces.PSSession])
       {Write-Host "Remote test succeeded: $ComputerName."}
   else
       {Write-Host "Remote test failed: $ComputerName."}
}

Step 5: Link the Two Functions Together

The script starts with CanPing, and then moves onto the CanRemote function in this part of the script. If CanPing fails, then the script won’t move onto the next part of the script and will stop. If the CanPing is successful, then the CanRemote function gets executed afterward.

This is a very handy script for teaching you some of the basic principles of how to create functions and parameters within Powershell.

#Step 5
if (CanPing $ComputerName) {CanRemote $ComputerName}

Having Trouble Running the Script?

If you tried to run this script and got error messages, check and see if you have your execution policy set to run scripts on your computer. For a more detailed explanation on how to do this, check out Garth Schulte’s PowerShell training. Garth covers everything we discussed in this post and more. So, if you are stuck or want to build your PowerShell knowledge, Garth can help you out.  

Wrapping it Up

PowerShell can help you to do almost anything you need via the command line. It is heavily integrated into the Windows environment. It also works on Active Directory servers, meaning tasks such as importing new users can be turned into a quick task instead of using the GUI and taking much longer in the process.

PowerShell automates many daily tasks, freeing you to pursue more meaningful work while scripts get through the monotonous tasks. PowerShell skills are vital to build, whether you are a system administrator or a DevOps engineer. Don’t wait to start learning PowerShell.

 

Not a CBT Nuggets subscriber? Start your free week now.

CBT Nuggets has everything you need to learn new IT skills and advance your career — unlimited video training and Practice Exams, Virtual Labs, validated learning with in-video Quizzes, Accountability Coaching, and access to our exclusive community of IT professionals.

Learn more about the CBT Nuggets Learning Experience.

 

Comments are closed.