PowerCLI: Lesson #2
As I go through this serious of lessons on PowerCLI I’m going to try to expose the basics of PowerShell in the same lessons. 2 for the price 1. I’m going to initially deliver them in very small nuggets scaling larger as we advance into more detailed stuff. So in this lesson I’m going to look at a some core fundamentals of PowerShell whilst applying the theory to PowerCLI.
First let’s look at a process known in PowerShell as the “pipeline”.
Most cmdlets (commands) provide some form of output when you run them, for example when we ran the Get-VM the output was a list of VMs and some basic information. With the “pipeline” function we can take this output and process it through a follow-up cmdlet. This is done by placing the | character after the command then entering the follow-up command. We can use another cmdlet Where-Object to filter out information from the properties of the previous cmdlet.
Now we mentioned in lesson 1 that cmdlets have properties and methods and one of those properties found with the Get-VM cmdlet is PowerState which you can guess it is used to report the power state of a VM (powered off, on etc) . So to list all VMs that are powered off we would run the Get-VM cmdlet and pipe it into the Where-Object cmdlet and would look like this:
So when we execute that command we get a list of just the powered Off VMs:
Change the command to filter “PoweredOn” then we just get the powered On VMs:
So how do we find out what properties of the Get-VM cmdlet we can filter on. Well like any cmdlet we find out what properties and methods (actions) are available by passing (piping) the cmdlet into a another cmdlet to find the results. If you pipe any cmdlet into the Get-Member cmdlet the output will be a list of properties and methods. You can also use a predefined alias (alias use to abbreviate cmdlets) for Get-Member which executed by entering gm . So to get the properties and methods of the Get-VM cmdlet you could use:
So let’s take this idea one step further, let’s use a cmdlet Start-VM and I bet you can guess what that does… Let’s use it to start all the powered off VMs by piping what we know into it like this:
Which will start all the VMs that have the Power State of Powered Off.
Ok last thing I want to do here is just explain something about piping. The result of the Get-VM although look like a load of text is actually creating a list of objects (VMs in this case) . So the Start-VM cmdlet isn’t actually trying to start a VM called “SCOM PoweredOff 1 256” it just takes the Name property value as the reference for the VM which in this case is “SCOM” and starts a VM with the same name.
In a later lesson I’ll try an explain Objects as PowerShell is an object orientated scripting language so it’s very important but for now look out for lesson#3.
Leave a Reply
You must be logged in to post a comment.