Automation techniques and scripting skills are no longer optional for a systems administrator; they are a necessity! Powershell is the scripting language that’s behind this requirement. Since Microsoft has released the Powershell language it only continues to pick up steam and be implemented across dozens of platforms. Powershell is now not only a scripting language like VBscript it’s a fully featured management framework that you can’t afford not to utilize.
This course will take your position to the next level if you’re a:
Don’t get looked over for that promotion or new job. Learn Powershell today to keep up with the ever-changing IT culture and to help make your job so much easier through automation.
Welcome in! This lecture is a brief 1:33 introduction to this course. It will go over all of the sections coming up and provide a brief explanation of each concept you will earn in this Powershell course.
In this course you should to learn the core fundamentals of Powershell along with real-world scenarios. I intend for you to come away from this course with enough knowledge to solve simple Powershell problems. You'll have enough knowledge to also construct a Google query should the Powershell help system fail you. Finally, I'll be sticking with Powershell version 2 in this course.
You're not going to need a lot of scripting knowledge ahead of time. I start at the very basics of Powershell and expound upon the basic fundamentals. However, if you have previous software development experience and have a clue about networked computers you'll be golden.
In this course, you're going to come away with a few hours of hands-on Powershell experience. You will have a thorough understanding of the Powershell fundamentals which will greatly increase your Powershell Google Fu.
After this course, you're not going to inherently know how to script every problem you see but I'll at least give you enough knowledge to be able to create some constructive Google queries that'll get you where you want to go.
You will also receive your very own Powershell script that was built by none other than you. This script will incorporate all the lessons in the course into a single script that you can put to use as soon as you complete the course.
As we go along, I welcome you to not follow me and go off on your own. You have my permission. Break it 9 ways to Sunday but fix it. Me showing you how to do this won't be near as educational if you break it and fix it yourself. So with the formalities out of the way, let's get started on our journey to Powershell greatness.
In this section, we're going to put a face to Powershell and look back on where it came from. We'll discuss it's many uses such being used as an interactive console or cmd.exe replacement, a scripting language and also a full-fledged software development language. It truly is more than just a shell replacement.
We're also going to briefly look at it's birth from Monad to it's current version 4.0 as of late 2013 and a brief look at where the platform has come up from each version.
This section will be much shorter than the others. Even though learning the definition and history is important I feel that real-world experience trumps lecture every time. For all you sys admins, I didn't think you'd mind if I'd be brief with the formalities and get straight to work.
One use for Powershell is a simple replacement for command or cmd.exe (the old school command window). I'm sure everyone is familar with the Windows command line. As of Powershell, it can offically be retired. Powershell is a full replacement to the command window. Powershell includes the same functionality that cmd.exe did plus a whole, whole lot more.
Even though Powershell doesn't technically have commands like "cd", "dir" or "del" it's developers ingeniously created these as aliases to "official" Powershell cmdlets (which you'll learn about later). If you make the background black and the text while you'd never know you weren't in the old cmd.exe window.
I'm not going into a whole lot of detail here now because you've got an entire section coming up on the console but for now suffice it to say think of the Powershell console as just an imporved cmd.exe window.
Remember batch files? Do you still use them? If so, you're going to be blown away with what Powershell can do vs. an old-school batch file. Can you ever see a software developer "coding" in batch files? No. Batch files were always in us sys admins' back of tricks in case we ever needed to automate some simple task.
Would you believe Powershell is so "powerful" that it now blurs the line between admin scripting and full-on software development. There's even some training camps that separate Powershell courses for admins and for developers. That's a very robust scripting language!
Powershell gets it's power from the .NET software development language. In fact, Powershell was written in .NET and when you run actual Powershell cmdlets you're actually running .NET programs themselves.
For this core component, think of Powershell as a replacement/MONSTER upgrade to batch files. You'll see what I mean as the course moves on.
Powershell version 1 (originally codenamed Monad) was introduced in 2005. It was originally intended to just be a replacement for cmd.exe (your typical Windows command line) and cscript (the engine that executes VBscripts). It wasn't until 2007 when the Microsoft Exchange team fully embraced Powershell and built their entire product on top of Powershell. If you're a Microsoft Exchange admin you've undoubetedly seen how the Exchange GUI console shows the Powershell code that it's generating. The Exchange team really took Powershell to a different level and proved to everyone that it truly can stand on it's own.
2009 rolled around and version 2 was introduced. Version 2 was then installed by default on Windows 7 and Server 2008. Version 2 introduced a slew of new features such as background jobs, remoting, debugging and a whole lot of other things you have no idea what I'm talking about but WILL!
Then in 2011, Powershell was upgraded to v3.0 however not in the way many Powershell geeks would have liked. Version 3 was introduced as part of a larger package called the Windows Management Framework. Us geeks felt a little slighted that it couldn't have it's own release but oh well, v3 still is really cool! As with version 2, v3 was packaged up with Windows 8 and Server 2012.
Like I mentioned earlier, I'm not going to go on and on about all the history of Powershell. Sure, it's useful info but doesn't really apply to us admins getting stuff done so I'm sticking to that promise and continuing on.
Yay! You've made it to the first screencast-heavy section! In this section, I'm going to show you how to get Powershell installed (if it's not already) and help you get some minor configuration changes done. For the most part, Powershell comes ready to go out of the box, however, I always recommend a few actions prior to really giving it everything.
In this lecture, we'll concentrate on upgrading Powershell to version 3. We'll go over how you can find out which version you're currently running, where to download version 3 from and how to get Powershell version 2 upgraded to version 3.
0:10 - Verifying Powershell v3 is installed.
0:20 - Checking the version in the console.
0:43 - Resizing the console window for easy reading
1:47 - Setting the screen buffer size to save more console output
2:56 - A brief overview of the help system and how to get it updated
3:48 - Setting your execution policy
As you saw in the Powershell background section, one of Powershell's purposes was to replace cmd.exe; what I call the interactive console. In this section, I'm going to go over some of the differences between working in the Powershell console vs. the old command line console. In the other lecture, I'll also be discussing profiles. If you have any experience with the Bash shell in the Linux world, you'll be familar with profiles. In this section, I'll be introducing you to profiles and showing you how you can use them with your daily activities.
0:12 - How to know you're in the Powershell console
1:17 - Explaining Powershell console history
2:00 - Tab completion in the console
2:50 - Using the Ctrl key to quickly navigate
0:05 - The ISE editor
0:42 - What's a Powershell profile path?
2:21 - Finding the default profile
3:45 - Editing the profile to create your own
What are cmdlets?
Cmdlets pronounced "command lets" are tiny .NET programs that Powershell uses to get things done. Cmdlets are used for everything in Powershell. Think of a cmdlet as a Windows executable or a DOS batch file. Either one you type in a few characters in the command window, it executes and does something. At it's most basic, this is a Powershell cmdlet.
In the first lecture, I'll show you how to see all of the cmdlets available to you. I'll also briefly explain how all cmdlets are named. You'll learn that one of Powershell's best traits is it's focus on simplicity and standardization. The specific naming convention is one of those traits.
The Help System
The third topic we're going to cover is the help system. Naturally, when I mention help system to an IT admin I'd get tomatos thrown at me. No one really likes to actually read the manual, right? Well, you're going to be surprised on how well the Powershell help system is put together. Gone are the days of Googling your brains out for hours trying to figure out a small nuance with the way VBscript treats a variable. Powershell's help system is simple to use, intuitive and even has a method to keep it up to date.
Using Powershell Aliases
Finally, we'll discuss cmdlet aliases. You'll see that an alias in Powershell is simply another name for the same cmdlet. That's it. Pretty simple. I'll show you two types of aliases; user-defined and default. User-defined aliases are all the aliases you, as the user, create yourself. Default aliases are those that come built-in with Powershell. In the screencast, I'll get to show you how to manage both types of aliases.
0:17 - Using Get-Command to find cmdlets available to you
3:46 - Introduction to Powershell's help system
0:11 - Finding aliases in your current session
1:18 - Creating your own aliases
1:53 - Default aliases
2:30 - Many default aliases for a single cmdlet
2:58 - How to export aliases to share
What are variables?
Like all other scripting/software development languages, Powershell has variables. Variables are as ubiquitous as cmdlets are in Powershell. Variables behave similarly in all languages such that they are a container to store things. The contents of these containers can be any data type (which we will cover), multiple data types, or other variables.
The basic uses for variables is to first store something we'll be using later in a script or to be used to store the result from the running of a script. There are all kinds of ways to use these containers and in this section I intend to break down variables for you and show you how Powershell leverages them.
Variable Data Types
The first topic on variables we'll be going over is data types. Every variable in Powershell has a specific type; a data type. A data type is basically a way to define how a variable is going to behave and what's it's going to contain. There are dozens of data types in Powershell. However, I will only be covering 5 of the most common ones in the upcoming screencasts.
Data types can be either explicitly defined or just assumed. Powershell is what's called a dynamically typed or loosely typed language. This means even though you may create a variable as one type it won't necessarily stay at that type for the lifetime of your script. In a lot of instances, Powershell is smart enough to change the type depending on the context instead of failing.
In the final screencast of the section we're going to cover the basics of managing your variables. I'll show you how to create variables multiple ways, how to update them with different contents and finally a less used function of actually destroying them to free up memory.
0:19 - What's a variable?
1:11 - Assigning values to variables
1:32 - Reading a value from a variable
2:25 - Quick intro to data types
3:01 - Removing variables
0:44 - Creating a boolean variable
1:31 - Testing boolean variables
1:56 - Setting type explicitly
3:23 - How to find out the type of variable
0:16 - Creating string variables
1:48 - The difference between a single and a double quote string
0:04 - Creating integers
0:53 - Math with integers
1:33 - The difference between 1 as a string and 1 as an integer
2:20 - String concatenation
0:06 - What's an array?
0:51 - Creating arrays
1:56 - Adding elements to arrays
2:36 - Introduction to array indexes
3:55 - How to find the number of elements in an array
0:20 - Creating a hash table
1:42 - What's a key/value pair?
3:48 - Showing a real-world example of the use of a hash table
4:13 - Reading from a hash table
5:15 - Adding key/value pairs to a hash table
6:14 - Modifying a hash table
7:12 - Removing key/value pairs from a hash table
An Introduction to Conditional Logic
When writing a script in Powershell it's commonplace to come to a point where you must make a decision about where it needs to go. It's extremely common to have something like a crossroad in your script where it must choose a path to take based on the current environment. This "crossroad" is generally called conditional logic. It's called conditional logic because a decision on which way to go is based on 1 or more conditions. From that decision comes an outcome.
In the real-world, a common way to portray this is with an "if". For example, let's say "If" I vacuum the carpet then my wife won't get mad at me. Notice with the "if" generally comes a "then" afterwards. In this situation, there's 1 condition (I vacuum the carpet) and an outcome (my wife doesn't get mad at me).
That's all well and good but in this example there can only be 1 outcome (my wife doesn't get mad at me). What's supposed to happen if I take a risk and choose NOT to vacuum. We have no condition for this. We need another outcome. Now, let's try if I vacuum, my wife doesn't get mad at me else my wife is happy with me. Notice the "else" addition? By adding the "else" this allowed us to define all of the outcomes that are possible instead of just 1.
There are a few different ways to create this "crossroad" in our script but if you understand these examples you'll understand what we're doing in Powershell.
The If/Then/Else Construct
The first screencast we'll be going over on conditional logic is the classic if/then/else construct. This construct has been a staple of programming languages for decades and it's obviously part of Powershell as well. This construct as well as the slightly more complex if/then/elseif/else construct is in nearly every script I write and will most likely show up in a lot of your scripts as well.
This is a simple but very powerful method of designing your scripts in Powershell. It is important that you understand the if/the/else construct and how to use it. Fortunately, by using plain English terminology, Powershell makes learning this concept a lot easier so let's see what we can do with it.
The Switch Statement
In our final screencast, we're going to discuss the switch or case statement. The switch statement is another piece of conditional logic but might not be as easy to understand as the if/then/else construct. However, it works nearly identical.
A switch statement is identical to the if/then/else statement in that it still allows you to choose outcomes based on certain criteria. However, the way in which it's written can be much cleaner and easier to read than a typical if/then/else statement. Switch statements generally work better in situation where you've got a lot of conditions.
Let's say you've got 6 different conditions to test. Using if statements you'd have to have if/then/elseif/elseif/elseif/elseif/elseif/elseif/else. It can get pretty ugly vs. a switch statement where you'll see it'll be much cleaner looking in your script.
0:23 - The simplest if/then statement
1:59 - The if/then/else statement
2:58 - The if/then/elseif/else statement
3:45 - The if shortcut to test for the presence of a value
0:11 - When should a switch statement be used
0:33 - A switch statement overview
2:16 - A wildcard switch statement
What's a Loop?
Inevitably, there's going to come a time when you're going to be dealing with more than just 1 item at a time. Whether it be computers, users, files, folders, registry keys, etc. Any IT admin, even a beginner using Powershell, is going to have many instances where you need to deal with more than one item at a time. To do this, you've got to get looping.
A loop is a method of what's called iterating over each item. A loop defines the method you use to inspect each item of the group you're processing. To put a real-world example with this, let's say you've got 10 apples in front of you and you want to see which ones will be the best for an apple pie. You know you don't want any soft spots in them so you begin to check each one. In Powershell terms you're entering the loop by picking up the first apple. You check for soft spots and set it down. You've now went through 1 iteration of the loop. You pick up the next apple and do the same until you get to the 10th apple and set it down. From what point on, you're out of the loop.
Powershell has a few different ways of defining loops for different circumstances. In this section, I'm really going to concentrate on real-world examples in the lectures. This seems to be the best way to explain our loop concepts. Let's see what we can do with loops in the upcoming screencasts.
For our first screencast on loops we're going to discuss For loops. For loops are typically chosen when you know how many iterations you're going to do. Let's look at a real-world example of a for loop.
Going by our previous example of 10 apples, a for loop would be great for this application since we know the total number of apples. We'd simply specify in the for loop to only iterate 10 times and then stop. However, typically, it's not this easy in a script but I believe this will give you a good idea until we can get into screencast coming up.
Our next loop we'll be discussing is the foreach loop. The foreach loop is very similar to the previous for loop we talked about but it has 1 difference; the number of items isn't known ahead of time. In our apple example, we knew we were going to start out with 10 apples so a for loop would work great. Now, let's say we've got a bucket of apples and we don't know how many are there. In this case, a foreach loop would work out best.
Since a foreach loop doesn't know the total number of items ahead of time it simply takes each item one at a time. When it sees the last item in the group, it stops. Typically, a foreach loop is slower than a for loop for this reason. However, it is more common due to it's simplicity as you'll see in the upcoming screencast.
Do/While loops are pretty different when compared to the previous loop types we've discussed so far. A Do/While loop doesn't care how many items are in your group at any time. It simply performs a set of actions over and over again until something else happens.
Bringing up our old example of apples let's say you've got all your apples out and you've got water boiling to make some apple cidar. You begin to check the apples while the the water boils. Since you don't want it to boil over you continually check it while you're checking the apples. The moment you notice it start to boil over you then stop checking the apples. This is a do/while loop. It's a loop that happens only while something else is true. In this case, you would only check the apples while the water was boiling.
Manipulating the loop
As with the real-world, the Powershell loop isn't always cut and dry. Sure, you know you've got your 10 apples and you want to iterate through them. However, you get a call from the supermarket where you bought the apples and they tell you that there's been a recall on apples and they're all bad. At this point, you don't care about any of the apples anymore. It's time to break the loop. By inserting a break inside your loop, you're essentially saying just get me out of here now. You don't care what's the next iteration coming up. You're done.
Another common construct for manipulating a loop is the continue construct. You'd use a continue when, for example, you notice immediately without even picking up the next apple that it's got a worm in it. There's no need to even check for the soft spots. You simply want to continue past it and go onto the next apple. This is where you'd "continue" to the next iteration.
0:14 - What's a for loop look like?
0:53 - A demonstration of how a for loop operates
3:08 - Using real-world data in a for loop
4:03 - Using a variable index in an array with a for loop
0:15 - Using a foreach loop to iterate through an array
1:51 - Getting the contents of text files with a foreach loop
0:06 - An explanation of the behavior of a do/while loop
2:16 - Using a do/while loop to do something while a process is running
0:15 - Using the break construct to stop a loop before it ends
3:19 - Real-world data example using the break construct
4:08 - Using the continue construct to skip a loop iteration
7:44 - Real-world data example using the continue construct
We’re finally getting into the good stuff now. Objects are what makes Powershell..well…so powerful! They are really what make up Powershell. Add the infamous Powershell pipeline into the mix and you’ve got an awesome combination of usability, flexibility and power to make a script do just about anything you can think of.
Creating and Managing Objects
In the section on variables I fibbed a little bit. I only told you there were only 5 different common types of variables. Actually, there are 6. I didn't include the grand-daddy variable; the object. The reason was because objects in Powershell are what makes it stand alone from it's predecessor the old cmd.exe command line. Technically, objects are variables but they are in a league of their own.
Objects are the yang to Powershell's ying. Without objects, Powershell would be far less powerful and might as well be a typical DOS prompt. If you want to get real technical, all variables in Powershell are objects. That's how important they are! Let's break down what an object is and why it's so important to Powershell.
An object is a special variable that contains methods and properties. Methods are the actions you take on the object and the prperties are the attributes of the object. For example, recall how say a string just contained a simple text snippet like 'bob'? That's it. That's the end of that variable. There's nothing else to talk about. Now, let's say you've got a variable containing an object called 'Person'. You've now got something with some teeth! A person can run, walk, talk and eat (methods). A person has hair, skin, a personality, and an attitude (properties). Think of an object as a mainframe computer while a common variable like a string, integer or array is simply a dumb container.
Objects have revolutionized computer programming in general. OOP (or object oriented programming) has countless books written on thet topic and is sort of a religion in the development world. We're not going to get into that by any means. However, we will be seeing tons of examples of what objects can do in Powershell!
The Powershell pipeline can be thought of as a factory floor. Every factory floor has a station for various functions. Let's say we're building a car. To build a reliable car, you've got to bring in the parts, slap on the doors and the exterior, put the interior in and finally put a nice paint job on. A factory has a serial line of processes that happens until the car is rolled off the line. You can't apply the paint until the doors are on, for example.
A Powershell pipeline is very similar to this. The output of one process turns into the input of the next process. However, instead of car parts, objects are passed down the line and manipulated as necessary.
The pipeline is one of those unique characteristics of Powershell. If you're like me, you'll soon find yourself using the pipeline more in the console and less in your scripts but you're welcome to use it in either place.
0:12 - Using the Get-Member cmdlet to find object information
2:20 - Using Get-Member to find the status of a service
3:04 - How to find all the object information with Select-Object
4:00 - Getting the object methods and properties of a process
4:21 - Stopping a service using a Powershell object
6:23 - Comparing objects with Compare-Object
8:26 - What's a custom object and how to create them
11:16 - Sorting the output of an object with Sort-Object
13:24 - Using Select-Object to only get specific properties
0:27 - What's this pipeline thing?
0:59 - A theoretical pipeline example
2:13 - Applying a filter to the pipeline with Where-Object
4:28 - Using the pipeline to get specific files from a directory
6:25 - Using the pipeline to get all services sorted by status in one line
7:40 - Formatting the output of the pipeline with Format-Table
8:31 - Using Out-GridView to get an Excel-like window to view output
In this section we’re going to be going over WMI and how you can use Powershell to leverage the data in the WMI repository. Using Powershell makes it easier than ever to get information from a Windows computer like processor, memory, hard drive, etc. For those not familiar with WMI, I’ll briefly go into an overview and finally we’ll discuss how Powershell can interact with WMI.
The Basics of WMI
WMI or Windows Management Instrumentation is a framework designed to allow an administrator to mimic just about anything that you can do with the GUI. With WMI, you can both read data about a computer for something like free hard drive space or even change information on a computer such as creating a printer. You can easily do both of these with the GUI but with WMI you can script these tasks.
WMI comes preinstalled on all Windows computers from Windows 2000 and newer. WMI is actually Microsoft's implemtentation of the WBEM or Web-Based Enterprise Management standard. WMI was designed to provide a standardized way for applications (Powershell, for example) to interface with a Windows computer. For the newcomer to WMI and Powershell, just think of it as the method Powershell uses to exchange information with the internals of Windows.
What Makes Up WMI
WMI is broken down into namespaces, classes and attributes. Namespaces are a logical grouping of classes. By default, Windows has a namespace in which you will gain a lot of experience with which is rootcimv2. This means that there's a cimv2 namespace inside the root namespace. Don't get caught up in what it means. There are whole books dedicated to WMI. For this course, we'll just be sticking with that namespace.
Inside namespaces, you'll find classes. Each class in th cimv2 namespace is broken down by computer function. You'll see classes called Win32_ComputerSystem, Win32_LogicalDisk, Win32_Processor and so on. Inside each of these classes you'll find objects (not Powershell but WMI objects). The objects inside each class is typically pretty self-explanatory. For example, what would you expect to be in the Win32_Processor class? All of the processors installed in the computer, maybe? Yep! As with objects in general, you'll also find methods and properties attached to each of those objects.
Don't worry if all of this isn't syncing with your brain. I assure you once you see the examples, it'll bring a lot of clarity to WMI.
Using Powershell to Interact with WMI
During the VBscript days, in order to query WMI you’d have to have at least 4 lines of extremely hard to read code. With Powershell, it’s all been wrapped into one succinct cmdlet called Get-WMIObject. Get-WMIObject will be the de facto cmdlet to use when reading information from WMI. As you progress in your Powershell greatness you may run into other WMI cmdlets but for this beginners course we’re only going to concentrate on reading from WMI. To this day, for my job, this is the cmdlet I use the most.
0:05 - Quick intro to what WMI is
1:05 - Where to find the WMI repository on the file system
1:41 - Finding namespaces in the WMI repository
2:56 - Using wbemtest to look over WMI classes
3:25 - Using Get-WmiObject to list all classes in a namespace
4:20 - How to find WMI classes relating to disk drives
7:18 - How to find all WMI objects in a class
0:23 - Finding property values from Win32_ComputerSystem with Get-WmiObject
1:17 - Introduction to WQL and an example of how to use
2:50 - Using WQL to select only specific properties to see
3:21 - Using Get-WmiObject to find free disk space on all hard drive partitions
3:45 - Saving time by using an alias for ForEach-Object
4:30 - Wrapping a pipeline object property inside a string
6:02 - Using MB, GB, KB, etc in Powershell
7:02 - An example of data rounding
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.