Learning PowerShell – Lesson Ten
PowerShell Lesson Ten
By: Steven Aiello
Teach Your Self PowerShell – Building a Working Interactive Menu!
Warning! This is an important lesson; in this lesson we are going to take almost all of the concepts that we have spoken about up until this point and put them together. If there are any concepts that you felt we unclear go back and review them before moving on through this lesson.
In this lesson we are going to create a script that will display based on your choice the services or processes running on the system. This script will give you the option to list all running processes, terminate a running process, list all the services on the system and their running states, start a stopped service, or stop a running service. This is a simple yet powerful script that you can use in your day to day environment.
Note to interact with running processes and services from PowerShell you will have to run Windows PowerShell ISE as an administrator.
In previous lessons I’ve provided the code in a step by step fashion, however, in this lesson you will be expected to review the previous lessons to build the complete interface. We will however take you through all the logical steps needed to build the script and provide you with an “almost” final product which you will have to complete. I recommend that you don’t look at the “almost” final product until you’re done with your code so you’re not influenced by my sample.
Step One Building the Scene
The first thing we will want to do in our script is to clear the screen of any garbage
Second we will want to establish all the variables needed for the script to execute properly. As a hint in my script I had 6 main variables that I used to complete these tasks.
You will want to establish a loop that will allow the user to run the script over and over again as long as they enter the expected input.
While the user is inside the running loop they should be presented with a menu that lists the following options
List all processes
Stop a process (by Process ID)
List all system services
Stop a running service
Start a stopped service
One the user is presented with the menu they should be prompted to enter in their selection and store that value into a variable.
By using that variable you should look for a predefined set up conditions and pick the code that executes based on the value the user entered.
The code paths executed should be appropriate for step 4.
As a bit of advice generally “Switch” statements are good for menu lists who predefined values. The final default can be used to catch any data that was entered in by the user that may not be valid.
Works on this script until it’s completed you’ve learned everything that you needed to complete it in previous lessons. Only look at the “almost” finished code if you legitimately get stuck. I will post the “almost” finished code as an image so you can’t simply copy and paste it into your PowerShell ISE editor!