Sei sulla pagina 1di 25

PowerShell Essentials (Part 1)

by Brien M. Posey [Published on 19 Aug. 2014 / Last Updated on 19 Aug. 2014]


This article series is designed to serve as a PowerShell tutorial for administrators who might not have taken the time to learn
PowerShell.
Last week I received an E-mail message from an IT pro who had just lost his job to corporate downsizing. Needless to say, he was
anxious to find another job, but he didnt ask me for employment. Instead, he asked me what was the single most important thing that
he should focus on learning right now.
While this question sounds really simple, it was actually quite provoking. After all, there is so much going on in IT right now. I thought
about telling him to focus on server virtualization or perhaps software defined networking. Ultimately, I told him to learn as much as he
could about PowerShell. PowerShell is used in most of Microsofts current line of server products, and there are no signs that it is
going to go away any time soon. Although basic administrative tasks can usually be performed through a GUI, administrators must
often delve into PowerShell to make infrastructure level configuration changes. While this certainly does not hold true in every case, it
is becoming more and more common to have to perform tasks through PowerShell.
During one of my visits to Redmond a while back, I had the chance to chat with someone who worked on the Exchange Server team. I
asked why so many tasks within Exchange Server had to be performed through PowerShell. The answer that I received kind of
surprised me.
It was explained to me that in some ways, the extent to which Exchange Server administration requires PowerShell had to do with
protecting less experienced administrators from themselves. Basic administrative tasks could be performed through the management
console, but in many cases low level configuration changes or potentially destructive operations had to be performed through
PowerShell. The presumption was that if an administrator knew enough to use a PowerShell cmdlet, they probably also knew enough
to safely perform the intended administrative action. In other words, performing an administrative task through PowerShell requires
intent. You cant get yourself into trouble by accidentally clicking on something (at least not in PowerShell itself).
The ironic twist is that there are plenty of administrators who do not want to use PowerShell. I dont say that as a way of being
condescending, or of insulting anyone. Its just that over the last few years I have spoken to and received email messages from quite a
few administrators who have expressed frustration with PowerShell.
In some ways, I can understand the frustration. I will be the first to admit that some of the blocks of code presented in TechNet articles
look like gibberish. Believe it or not though, PowerShell isnt nearly as difficult to use as some of the blocks of code shown in TechNet
articles might make it seem. The reason why some of the PowerShell examples that you might find on TechNet are so
incomprehensible is because PowerShell allows for the use of command abbreviations. For example, the cmdlet (pronounced
command-let) Format-List can be abbreviated as FL.
Cmdlet abbreviations are great for PowerShell experts who want to keep commands short and sweet, but when you cram together a
long string of abbreviated cmdlets, the command string begins to look like a bunch of random characters.
Im actually getting a little bit ahead of myself. I will talk about PowerShell cmdlet abbreviations later on in this article series. For right
now, let me just say that I have one simple goal for this article series. Because I believe that PowerShell is an essential skill for
Microsoft server administrators, my goal is to teach you the fundamentals and to make learning PowerShell as painless as I possibly
can.

Basic Command Syntax


As I previously mentioned, PowerShell is based around the use of cmdlets. A cmdlet is a verb noun combination. A verb is a word
that describes an action, while a noun refers to an object. That being the case, a PowerShell cmdlet is made up of two words. The first
word (the verb) tells Windows what action you want to perform, while the second word (the noun) tells Windows what type of object
you want to perform the action on.
To give you a more concrete example, consider the cmdlet Clear-Host. The verb in this case is Clear and it tells Windows that you
want to clear something. What needs to be cleared? The host. As such the cmdlet clears the screen.
Incidentally, if you grew up with DOS like I did, you will be happy to know that most of the old DOS commands work in a PowerShell
environment. For example, the DOS command for clearing the screen was CLS. The CLS command can be used in PowerShell as an
alternative to the Clear-Host command.
Advertisement

Why are there so Many Cmdlets?

Windows Server 2012 R2 has thousands of PowerShell cmdlets built into the operating system. As if that were not enough,
PowerShell is extensible. Microsoft provides modules that add additional PowerShell cmdlets that allow you to perform more
specialized tasks. Furthermore, Microsoft server products that are based around PowerShell also have their own sets of cmdlets. You
can even develop your own custom cmdlets if you want.
Since there are thousands of native PowerShell cmdlets and many more cmdlets that can be added onto PowerShell, one cant help
but to feel a little bit intimidated and to wonder why Microsoft has created such a large number of cmdlets.
There are a couple of different reasons why so many cmdlets exist. The first reason is that Microsoft wanted to keep things simple. I
know that sounds crazy, but hear me out.
If you have worked with some of the native Windows command line tools (executable files, not PowerShell), you probably know that
some of the tools are really complicated to use. A command line executable might have a long list of switches that can be used in an
effort to accomplish numerous different tasks. This is precisely the sort of thing that Microsoft tried to avoid when they created
PowerShell.
Rather than creating a set of complex, multi-purpose commands, Microsofts vision for PowerShell cmdlets was to create super
lightweight commands that do one thing, and one thing only. Since each cmdlet performs a very specific task, the cmdlets can be
linked together to perform more complex, multi-step processes.
Now admittedly, many PowerShell cmdlets do support the use of optional parameters. Even so, most of the cmdlets are fairly
straightforward to use.
The other reason why there are so many native PowerShell cmdlets is because of the way that the basic syntax works. As you will
recall, each cmdlet is made up of a verb and a noun. Each verb has multiple uses, as does each noun. For example, there are dozens
of cmdlets that use the Get verb. In other words, verbs and nouns are designed to be modular so that they can be used together in
various combinations. Each combination constitutes a different cmdlet. Thats why there are so many cmdlets.

Conclusion
In this article, I have spent quite a bit of time talking about the basic syntax used in PowerShell cmdlets and the reasons behind that
syntax. In Part 2, I want to begin showing you how to actually use some PowerShell cmdlets.

PowerShell Essentials (Part 2)


by Brien M. Posey [Published on 16 Sept. 2014 / Last Updated on 16 Sept. 2014]
This article continues the PowerShell Essentials series by explaining how to figure out which cmdlet to use to complete a task.

Introduction
In the previous article in this series, I talked about the basic syntax used by a PowerShell cmdlet and I talked about Microsofts
rationale for constructing cmdlets in this way. For those who might be wondering why I started out talking about something so basic, I
did it because it fits within my primary goal for this article series.
My hope for this series is that I can help you to feel more confident about using PowerShell and get rid of PowerShell related anxiety.
The reason why I started out by talking about the basic cmdlet syntax was to illustrate that even the most complicated PowerShell
scripts are really nothing more than a long series of simple tasks.
Obviously, knowing the basic cmdlet syntax is just a starting point. There are some other things that you need to know in order to
become proficient with PowerShell. That being the case, my plan is to compile a list of some of the most common questions about
PowerShell and then answer those questions. Some of the questions that I want to address in this article series are:

How can I figure out which cmdlet to use?

How do I specify parameters for a cmdlet?

How can I get help with using a cmdlet?

How can I retrieve information about an object?

Why do some blocks of code not appear to be written in PowerShell?

How do PowerShell Scripts work?

Can I use variables?

How do PowerShell functions work?

By the time that I have finished answering these eight simple questions, you should have a solid working knowledge of PowerShell. Im
not saying that you will be an instant PowerShell expert, but by understanding the answers to the questions above, you should be able
to accomplish just about anything necessary in PowerShell.
Advertisement

How Can I Figure Out Which Cmdlet to Use?


I want to get started by answering the first question on the list how can I figure out which cmdlet to use? As previously explained,
cmdlets are the basic building blocks of PowerShell. Each cmdlet performs a simple task and multiple cmdlets can be joined together
to perform more complex tasks. Therefore, knowing which cmdlet or cmdlets to use in a given situation is the first step in completing
the task at hand.
In spite of PowerShells reputation for being complicated, some cmdlets are actually very intuitive. That being the case, it is sometimes
possible to guess the correct cmdlet. Dont believe me? Let me prove it.
As I explained in the previous article, PowerShell cmdlets are made up of verb-noun combinations. The verb indicates the action to be
performed, while the noun indicates the object to perform the action on. Even though PowerShell contains many thousands of cmdlets,
the list of usable nouns and verbs isnt as long as what you might expect. This means that sometimes it is possible to ask for what you
need in plain English.
Suppose for instance that you wanted to use PowerShell to retrieve the current date. You could do so by using the Get-Date cmdlet. In
this case, Get is the verb, and Date is the noun. A plain English cmdlet gave us exactly what we needed.
Admittedly, PowerShell wouldnt have a reputation for being complicated if everything were that easy. Fortunately, there are a few
other tricks that you can use to figure out what cmdlet to use.
One trick is to use a reasonable guess to figure out what you dont know. Suppose for instance that you were working on a Windows 8
desktop and you wanted to see information related to the hard disk that is installed in the system. Your first thought might be to use
the Get-Disk cmdlet. Get-Disk is a valid PowerShell cmdlet, but it is usually used with Windows Storage Spaces. That being the case,
using the command locally on a Windows 8 desktop yields an error message. So what do you do?
Think about the task at hand. You are trying to retrieve disk related information, so the Get portion of the command is probably correct.
One thing that you can do is to use the Get-Command command to determine all of the cmdlets that use the word Get. The command
for doing so is Get-Command Get-* As you can see in Figure A however, the list of cmdlets that use Get is pretty long.

Figure A: You can use Get-Command to retrieve a list of cmdlets.

Maybe it would be more helpful to get a list of disk related cmdlets. Since we are still trying to retrieve disk related information, we can
include the Get verb in our query. So, if you wanted to see all of the cmdlets that use the Get verb and some variation of the word disk,
you could use the following command:
Get-Command Get-*disk*
As you can see in Figure B, you get a much shorter list of results this time. Out of the list of results, the only cmdlet that really seems
plausible is Get-PhysicalDisk. If you look at Figure C, you can see the error message produced by the Get-Disk cmdlet and the results
returned by using the Get-PhysicalDisk cmdlet.

Figure B: These are the only cmdlets used for retrieving disk information.

Figure C: The Get-Disk cmdlet produces an error while Get-PhysicalDisk provides the information we wanted.
In my experience, it is usually possible to use the Get-Command cmdlet to locate the cmdlet that is required for a given situation.
Every once in a while however, the required cmdlet is something really obscure that I never would have guessed. Fortunately, there
are ways to get help in those situations.
Lets pretend for example that I wanted to use PowerShell to delete a storage pool, but dont know what cmdlet to use. My first guess
would probably be to use the Delete-StoragePool cmdlet, but that guess would be wrong. The Delete-StoragePool cmdlet does not
exist.
Next, I would probably use the trick that I showed you a moment ago and enter Get-Command Delete-*However, this produces no
results. Clearly, Delete is not the right word.
There are a few different things that can be done in this situation. One option is to try to use the Get-Command cmdlet against the
word StoragePool. The command for doing so is Get-Command *-StoragePool. In this case, PowerShell shows us four related cmdlets
and it is easy to tell that the cmdlet that we are looking for is Remove-StoragePool. You can see the results in Figure D.

Figure D: The command produced four different results.

OK, so that trick gave us the information that we needed, but what if it hadnt? What else could we do? Well, one option is to use the
Get-Help command. Since we know that we are trying to do something storage related, we could type Get-Help Storage. Doing so
would provide us with a list of storage specific commands, as shown in Figure E.

Figure E: The Get-Help Storage provides a list of storage related cmdlets.


Incidentally, the Get-Help cmdlet can also be used to get help with the cmdlet syntax. For instance, if you type Get-Help RemoveStoragePool, you will see the cmdlets full syntax, plus the contents of any available help files, as shown in Figure F.

Figure F: You can use Get-Help to retrieve cmdlet syntax.


If the techniques that I have demonstrated do not work, then you can always use the Internet. You can for example perform an Internet
search on the phrase use PowerShell to remove a storage pool.

PowerShell Essentials (Part 3)


by Brien M. Posey [Published on 16 Oct. 2014 / Last Updated on 16 Oct. 2014]
This article continues the discussion of PowerShell by explaining cmdlet syntax and how to retrieve attribute values.

Introduction
In my previous article, I listed eight questions with the goal of helping my readers to feel more comfortable with PowerShell by
answering those eight questions. I answered the first question in the previous article, so now I want to move on to answering some of
the other questions on the list.
Advertisement

How do I Specify Parameters for a PowerShell Cmdlet and How Can I Get Help with Using a
Cmdlet?
Many PowerShell cmdlets can be used without the need for additional parameters (at least in certain circumstances). The Get-VM
cmdlet for instance, returns a list of Hyper-V virtual machines without you needing to specify any additional parameters. Often times
however, you will find that you need to specify one or more additional parameters in order to get a cmdlet to do exactly what you need
for it to do. So how do you know which parameters you can use with a given cmdlet?
There are a number of different techniques that you can use, but my advice is to take advantage of the Get-Help cmdlet. To use this
cmdlet, simply type Get-Help, followed by the cmdlet that you need assistance with.
To show you how this works, lets pretend that you needed to retrieve a list of the physical disks that had been previously retired from
your server. The Get-PhysicalDisk cmdlet is used to retrieve physical disk information, but how do you get information about retired
disks?
The first step in the process would be to get help on the cmdlet. The actual command that you would enter is:
Get-Help Get-PhysicalDisk
When you enter this command, PowerShell will display the full syntax of the Get-PhysicalDisk cmdlet. It is common for this syntax
information to be followed by usage examples, although Microsoft does not provide examples of how to use Get-PhysicalDisk. You
can see what the syntax information looks like in Figure A.

Figure A: Get-Help retrieves the full command syntax.


I will be the first to admit that the information that is displayed as a result of using the Get-Help cmdlet can be a little bit overwhelming.
However, things really arent as difficult as they might at first appear. The trick is to know how to read the syntax information. To show
you what I mean, lets take a look at the last block of text in the screen capture above.
The text starts out with Get-PhysicalDisk. Obviously this is the cmdlet that we are using. From there, you will notice the following text:
[-Usage <usage[]>
Anything that appears in brackets [] references an optional parameter. In this case, we have a bracket [ followed by Usage. This
indicates that Usage is an optional parameter.

The next thing that we see after Usage is <usage[]> this indicates that the Usage parameter requires some additional information.
You cant just use the command Get-PhysicalDisk Usage because even though Usage is a valid parameter, PowerShell needs more
information. It needs to know what kind of usage you are interested in. Any time you see a word in between the less than < and
greater than > signs, it indicates that you are going to need to provide some additional information to the parameter. So in this case, Usage is the parameter and <usage[]> is the additional data.
Of course this raises the question of where we can find this additional data. Well, it is included in the command syntax. You will notice
that the next section of the syntax is:
{Unknown | AutoSelect | ManualSelect | HotSpare | Retired | Journal}
You will notice that the list of words is enclosed in braces {}. These braces indicate that the words within can be used in conjunction to
the optional parameter. To show you what I mean, lets go back to the original example in which I wanted to find information related to
retired physical disks. To get this information, I could use the following command:
Get-PhysicalDisk Usage Retired
So you can see that I am appending the Usage parameter to the Get-PhysicalDisk cmdlet, and then I am telling PowerShell what
type of Usage I am interested in.
The syntax that is displayed within the above figure continues on, but the basic pattern repeats. The syntax information lists a number
of optional parameters and the data that can be used with those parameters. Some of the other optional parameters for instance are
Description, -Manufacturer, -Model, -CanPool, and HealthStatus, and the list goes on.

How Can I Retrieve Information About an Object?


At the very beginning of this article series, I explained that PowerShell cmdlets are based around verb-noun combinations. Nouns can
be thought of as objects, and nearly every object has attributes. An attribute is data that describes the object. To show you what I
mean, lets go back and take a look once again at the Get-PhysicalDisk cmdlet, which you can see in Figure B.

Figure B: Get-PhysicalDisk displays information about physical storage.


As you can see in the figure above, when I enter the Get-PhysicalDisk cmdlet, PowerShell displays each disks friendly name, whether
or not the disk can be pooled, its operational status, its health status, its usage, and its size. Each of these fields represents an
attribute of a physical disk.
There are two critically important things to know about this. First, knowing the names of the various fields (attributes) is key to being
able to function in PowerShell. After all, how can you identify a specific disk from within a PowerShell script if you dont know that the
disks identity is tied to an attribute called FriendlyName.
The other thing to know is that typically the Get command does not display all of the available attributes. There are typically some
additional attributes that are hidden from view. For example, PhysicalDisk has an attribute called Manufacturer, but that attribute is not
displayed by the Get-PhysicalDisk cmdlet.
One of the most important PowerShell skills to master is retrieving the names of the available attributes. Fortunately, its really easy to
do. You must simply append the Pipe symbol | and the Select-Object * cmdlet to the end of the cmdlet that you are using. For
instance, if you wanted to see all of the available attributes for the Get-PhysicalDisk cmdlet, you would use the following command:
Get-PhysicalDisk | Select-Object *
You can see the output of this command in Figure C.

Figure C: We are retrieving all of the PhysicalDisk attributes.


There are actually far more attributes than what is shown in the screen capture. It was impossible to fit all of the attributes on screen at
once. The column on the left lists the attribute names.
In case you are wondering, the * after Select-Object tells PowerShell to display all of the attributes, but you can display select
attributes instead. For example, suppose that I wanted to display the friendly name, serial number, spindle speed and physical sector
size for each physical disk. I could do it with the following command:
Get-PhysicalDisk | Select-Object FriendlyName, SerialNumber, SpindleSpeed, PhysicalSectorSize
You can see the commands output in Figure D. Remember that you arent limited to simply displaying attributes. PowerShell can
make decisions based on attribute values. In some cases it is even possible to set attribute values yourself.

Figure D: We can display a custom set of attributes.

PowerShell Essentials (Part 4)


by Brien M. Posey [Published on 18 Nov. 2014 / Last Updated on 18 Nov. 2014]
Share12
This article continues the discussion of PowerShell basics by explaining why some PowerShell code might not appear to use the
standard PowerShell command syntax.
Back in one of the earlier articles in this series, I listed several questions that I planned to answer in an effort to help my readers to
achieve proficiency in Windows PowerShell. Here is the list of questions once again.

How can I figure out which cmdlet toUsee?

How do I specify parameters for a cmdlet?

How can I get help with using a cmdlet?

How can I retrieve information about an object?

Why do some blocks of code not appear to be written in PowerShell?

How do PowerShell Scripts work?

Can I use variables?

How do PowerShell functions work?


I have already answered a few of the questions from the list, so in this article I want to continue the discussion by answering the
question of why some blocks of code appear to not be written in PowerShell.
As you have probably already figured out, I spend a lot of time working with PowerShell. Even though I definitely know my way around
PowerShell, I sometimes find myself visiting sites like MSDN or TechNet looking for scripts that can be used to accomplish various
tasks. After all, why reinvent the wheel if someone else has already posted a solution to the task.
I have to admit that the first few times that I downloaded a PowerShell script from TechNet, I was a little taken back. The scripts were
only vaguely similar to PowerShell (at least as I understood the PowerShell syntax rules). I wasnt even completely sure that I was
looking at PowerShell code.
There are actually a number of different things that can cause a block of PowerShell code to look a lot different from what you have
seen so far in this article series. Some of the things that can make PowerShell look completely foreign include:

Variables

Abbreviations

Operators

Comments

Scopes
Im not going to talk about scopes in this article series because scopes are a more advanced topic (I plan on eventually writing a
separate series that covers advanced scripting), and variables are going to be discussed later in this series. For right now though, lets
take a look at abbreviations, operators, and comments.
Comments
Comments are simply lines of readable text that are inserted into a PowerShell script for documentation purposes. A comment always
begins with a pound sign (#). Everything after the comment is ignored by PowerShell. Comments only exist as a way of documenting
what a script does. Here is an example of a PowerShell comment:
# This is a comment line.
Abbreviations
PowerShell abbreviations are simply a way to shorten a PowerShell cmdlet so as to reduce the amount of typing required. I have to
admit that PowerShell abbreviations are a bit of a pet peeve for me. I almost always prefer to write PowerShell code in long form
because I think that doing so results in code that is more readable and easier to understand. Even so, abbreviations are common
enough that it helps to familiarize yourself with them.
Let me show you an example of how a PowerShell abbreviation works. Suppose for a moment that I wanted to create a list of all of the
virtual machines that exist on a Hyper-V server and then format the information in table form. I could accomplish this task with the
following command:
Get-VM | Format-Table
The Get-VM portion of the command retrieves the list of VMs. The next thing that you see is the pipe symbol (|). The pipe symbol is
used to combine two cmdlets. The pipe symbol causes the output from the first cmdlet to act as input for the second cmdlet. So in this
case, we are taking the output from the Get-VM cmdlet and using it as input for the Format-Table cmdlet, which controls how the
resulting data is displayed. You can see what this looks like in Figure A.

Figure A: The Get-VM | Format-Table command creates a table displaying Hyper-V virtual machines.
So now that I have shown you how the Get-VM | Format-Table command works, lets get back to the discussion of PowerShell
abbreviations. The Format-Table cmdlet is often abbreviated FT. Hence, the command could be shortened to:
Get-VM | FT
As you can see, the abbreviated command barely resembles PowerShell. As you can see in Figure B, the abbreviated command
delivers the same output as the long form command. Another example is that Format-List is often abbreviated as FL.

Figure B: The Get-VM | Format-Table command can be shortened to Get-VM | FT.


Operators

Operators can be another source of confusion within PowerShell. Operators are comparative functions such as greater than, less than,
or equal to. The reason why operators are sometimes confusing is that the most common operators are expressed in an abbreviated
form.
The operators that are used within PowerShell include:

EQ (Equal)

NE (Not Equal)

GT (Greater Than)

GE (Greater Than or Equal To)

LT (Less Than)

LE (Less Than or Equal To)

Like

NotLike

Match

NotMatch

Contains

NotContains

In

NotIn

Replace
Admittedly, some of these operators are more commonly used than others. The most commonly used operators tend to be EQ, -NE, GT, -GE, -LT, and LE.
Since operators are such a big part of PowerShell, I want to take a few minutes and show you how some of these operators work.
PowerShell operators are used as a question. For example, you can ask if A is greater than B. The answer is sometimes Boolean
(True / False) or it may be numerical. PowerShell is usually smart enough to figure out which type of answer makes the most sense.
Suppose for instance, that I wanted to know if 6 was greater than 8. I could pose the question as:
6 GT 8
PowerShell would return an answer of false. Now suppose that I wanted to provide PowerShell with a list of numbers and then
determine which of those numbers was greater than 8. I could use a command like this one:
6, 7, 8, 9 GT 8
In this case, PowerShell would give me an answer of 9 rather than giving me a True / False answer. You can see an example of this in
Figure C.

Figure C: PowerShell can give answers in various formats.


You can also use the asterisks symbol as a wildcard. This tends to be especially helpful when it comes to matching comparisons. Take
this one for example:
Windows PowerShell Like *Power*
In this case, there would be a response of True.

You can also treat the Like operator as a which one is like operator. Suppose for example that I wanted to know whether the word
Windows or the word PowerShell was like the word Power. I could find out by using a command like this one:
Windows, PowerShell Like *Power*
The response should be PowerShell. You can see an example of this in Figure D.

Figure D: The Like operator can be used for comparisons.


Advertisement

Conclusion
In this article, I have explained why some blocks of code might not look the way that you would expect PowerShell code to appear. In
the next article in this series, I will continue the discussion by showing you how variables work. From there, we will move on to building
some PowerShell scripts.

PowerShell Essentials (Part 5)


by Brien M. Posey [Published on 20 Jan. 2015 / Last Updated on 20 Jan. 2015]
This article continues the discussion of Windows PowerShell by explaining how to use variables.
Throughout this article series, I have been working on answering some of the most fundamental questions pertaining to Windows
PowerShell. For those who are just joining me, the questions are:

How can I figure out which cmdlet to Use?

How do I specify parameters for a cmdlet?

How can I get help with using a cmdlet?

How can I retrieve information about an object?

Why do some blocks of code not appear to be written in PowerShell?

How do PowerShell Scripts work?

Can I use variables?

How do PowerShell functions work?


In the previous article, I answered the question of why some blocks of code appear to be written in something other than PowerShell.
In this article, I want to continue through my list of questions by explaining how to use variables.
If you have ever taken any sort of computer programming class before then you should be familiar with the concept of variables. A
variable is a named container that stores a value of some kind. You can assign a variable a value directly, or a variable can store a
calculated result.
Assigning a variable directly simply means telling PowerShell what value we want the variable to contain. Think back to math class for
a moment. We all remember expressions such as X=4. X=4 is an example of directly assigning a value to a variable. We are assigning
the value 4 to the variable X. Granted this isnt PowerShell code, but I wanted to give you a simplified example.
A calculated result means that you can base a variables value on the result of a calculation. For example X=2+2 is a calculated
variable assignment. We are still assigning X a value of 4 just as we did before, but this time we got there by performing a calculation.
OK, so now that I have talked a bit about variable assignments, lets take a look at how PowerShell does things. There are two things
that PowerShell does that makes it easy to work with variables.

First, you can use variables without first assigning them. I took several programming classes in school and many of the programming
languages that I studied required variables to be declared within a block of code at the beginning of the program. PowerShell doesnt
have this requirement. You can use a variable on a whim.
The other thing that PowerShell does to make your life easier is to precede every variable with a dollar sign ($). This makes it really
easy to spot variables.
So with that said, there are two primary methods for assigning a value to a variable in PowerShell. The first method involves using the
Set-Variable cmdlet. To show you how this works, lets pretend that I wanted to create a variable named $UserName and I wanted to
assign it a value of Brien. I could accomplish this by entering the following command:
Set-Variable Name UserName Value Brien
As you look at this command, you will notice that it doesnt make use of a dollar sign. The reason for this is simple. Because I used the
Set-Variable cmdlet, PowerShell was smart enough to know that it needs to add a dollar sign in front of the variable name.
So what about retrieving the value of a variable? Well, thats super simple. All you have to do is type the variable name. In this case,
we could find the variables value simply by typing $UserName. You can see how this works in Figure A.

Figure A: You can type a variables name to retrieve its value.


As previously mentioned, there is a second method that is commonly used to set a PowerShell variable. Remember when I used X=4
as an example of a direct variable assignment? Well, PowerShell is actually very similar. If I wanted to assign a value of 4 to a variable
named X, I could do so by using the following command:
$X=4
You can see how this works in Figure B.

Figure B: PowerShell allows you to assign a value to a variable without using the Set-Variable cmdlet.
Before I move on, I need to take just a second and talk about a couple of rules for variables. First, you will notice that I assigned two
different data types. I showed you an example of assigning a string value (Brien) and an example of assigning an integer value (4).
PowerShell is actually really flexible when it comes to variable assignments. Windows doesnt seem to care if you are assigning text,
numbers, or even blocks of code to a variable.
One thing that you do have to pay attention to however, is the variable name. There are certain words that you cannot use as a
variable name because the words are reserved by PowerShell. These are words that you can use in PowerShell without using a
cmdlet. For example, in the next article in the series I am going to show you how to create PowerShell functions. The word Function is
reserved and cannot be used as a variable. The same also applies to words such as If, ForEach, and Return.
So how can you put a variable to work? As you will recall, I showed you some of the operators that are supported by PowerShell in
one of the previous articles. These same operators can be used to compare the contents of a variable. This obviously isnt the only
way that you can use a variable, but it makes a good example.
Earlier, I set a variable called $X to a value of 4. Lets do a really simple comparison to see if $X is greater than zero. If it is bigger than
zero, we will type Bigger than Zero as a response. So here is the line of code that we will use:
If ($X GT 0) {Bigger than Zero}
At first glance, this looks like one of those really cryptic blocks of code that I talked about in the previous article, but there is a method
to the madness. This line of code is essentially an if then statement.
There are three parts to the command. The first part is the word if. This tells PowerShell that we are doing an if then.

The second part of the command is ($X GT 0). This is our comparison. $X is our variable. GT is a PowerShell operator that means
greater than. 0 is the value that we are comparing against. So in essence this part of the command is checking to see if the value
within variable X$ is greater than zero.
The last part of the command is {Bigger than Zero}. This simply causes the text Bigger than Zero to be displayed if the condition in
the second part of the command is true. Therefore the command could be summarized as if $X is greater than 0 then write Bigger than
Zero. You can see the command in action in Figure C.

Figure C: This command compares a variable against a static value.


Advertisement

Conclusion
In this article, I have explained how variables work within Windows PowerShell. In Part 6, I plan to conclude this article series by
explaining how functions and scripts work within PowerShell.

PowerShell Essentials (Part 6)


by Brien M. Posey [Published on 17 Feb. 2015 / Last Updated on 17 Feb. 2015]
Throughout this article series, my goal has been to answer some of the most commonly asked questions about Windows PowerShell
in an effort to give you a solid base of PowerShell knowledge. In this article, I want to wrap up the series by talking about scripts and
functions.
Lets start by talking about PowerShell scripts. A PowerShell script is really nothing more than a text file. The main idea behind
PowerShell scripts is that you may need to automate tasks, and scripts allow you to do that without having to manually enter a series
of command. Scripts are also useful when you want to create large blocks of code. In these types of situations, scripts not only make
your code reusable, they also give you the ability to edit your code.
Before I show you how to create a PowerShell script, I need to take a moment and talk about execution policies. When PowerShell
was first announced to the public (before it was ever made available), I remember writing that PowerShell was nothing short of a
dream come true for malware authors. I went on to theorize that PowerShell would make it a lot easier to develop malicious code and
that malware authors would soon be able to do things that they had previously only imagined.
The thing that kept my apocalyptic prophecy from coming true was the execution policy. An execution policy determines what types of
PowerShell scripts can be run on a system. Microsoft provides four different types of execution policies including:
Restricted This is the default execution policy. It does not allow scripts to be run. PowerShell cmdlets can only be entered manually.
AllSigned Scripts can be run if they are signed by a trusted publisher.
RemoteSigned Scripts can be downloaded and run if they are signed by a trusted publisher.
Unrestricted There are no restrictions on running PowerShell scripts.
It is worth noting that it is possible to create execution policy scopes and to use the Bypass parameter to block an execution policy or
to use the Undefined parameter to remove an execution policy from the current scope. Even so, the four execution policy settings
listed above are the most commonly used. If you want more granular control over execution policies then I recommend checking
out this TechNet article.
Setting an execution policy is simple. For instance, if you want to set the execution policy to unrestricted, you can use the following
command:
Set-ExecutionPolicy Unrestricted
So with that said, lets talk about scripts. As previously mentioned, a script is nothing more than a text file. The most commonly used
file extension for PowerShell scripts is .PS1.
If you think back to the previous article in this series, you will recall that I showed you a couple of lines of code that set a variable
called $X to a value of 4 and then later checked to see if X was greater than 0. If you look at Figure A, you can see that I have turned

those commands into a script by copying them to Notepad and then saving the file with a .PS1 extension. For the sake of
demonstration, I called the script MyScript.ps1.

Figure A: This is an example of a PowerShell script.


So how do we go about executing a script. Well, the first step is to make sure that the execution policy allows the script to be
executed. You can confirm the execution policy by using the Get-ExecutionPolicy cmdlet, as shown in Figure B.

Figure B: You can use the Get-ExecutionPolicy cmdlet to verify the execution policy that is in effect.
Once you have verified the execution policy, you can run the script by navigating to the folder containing the script and then entering ./
followed by the script name. To show you what I mean, lets run the MyScript.ps1 file. I saved my script to C:\Users\Brien\Documents.
Therefore, the commands that I would use to change to the correct folder and then execute the script are:
CD \
CD Users\Brien\Documents
./MyScript.ps1
You can see that this looks like in Figure C.

Figure C: You can use ./ followed by the script name to execute a script.
So now that I have shown you how to create and execute a script, lets turn our attention to PowerShell functions. A function is a block
of code that can be called by name. Normally, a function exists within a script and is used whenever a particular block of code needs
to be used more than once. Of course this isnt the only way to set up a function. A function can be used outside of a script. Since
functions normally reside in scripts however, lets modify our script to include a function.
I want to try to keep things simple, so I really dont want to add a big, complicated block of code to our script. Instead, lets use some
imagination. Lets pretend that our script is actually much longer than it really is. Lets also pretend that through the course of running
the script, the value of $X changes several times and that we need to periodically check to see if the variables value is greater than
zero.
In this type of situation, we could write an IF statement every time that the variable is assigned a new value, but that would result in a
lot of repetitive code. I always think it is better to write less code whenever possible because shorter code blocks are less prone to
coding errors.

So with that in mind, lets place our IF statement inside a function. Since functions have to be named, I will call the function VarCheck.
To declare a function, all we have to do is enter the word Function, followed by the function name and the code block that we want to
include within the function. The code block must be enclosed in braces {}.
So lets place our IF statement into a function called VarCheck. The function would look something like this:
Function VarCheck
{
If ($X -GT 0){"Bigger than Zero"}
}
Any time that you want to call the function, you must simply enter the functions name. If for example, we set the value of $X and then
wanted to check to see if $X was greater than 0, we could use the following lines of code:
$X=4
VarCheck
The entire function, with the script looks like this:
Function VarCheck
{
If ($X -GT 0){"Bigger than Zero"}
}
$X=4
VarCheck
Obviously this is a really simple example, but it illustrates the way that a function works. If we wanted to reassign and recheck the
value of $X a few times, we could do something like this:
Function VarCheck
{
If ($X -GT 0){"Bigger than Zero"}
}
$X=4
VarCheck
$X=0
VarCheck
$X=1
VarCheck
You can see the output of this script in Figure D.

Figure D: This script calls the VarCheck function several times.


Notice that each time we want to check the value of X, we are merely calling the function rather than retyping the comparison string.
One thing to keep in mind is that even though my sample function consists of a single command, you can just as easily create
functions that contain multiple commands.
Advertisement

Conclusion

I had originally intended for this to be the last article in my PowerShell essentials series, but I am going to write one more. The reason
for this is that in the real world it is sometimes necessary to pass parameters to a function and I didnt get a chance to talk about that.
Therefore, I want to spend Part 7 talking more about functions.

PowerShell Essentials (Part 7)


by Brien M. Posey [Published on 3 March 2015 / Last Updated on 3 March 2015]
In this article, I'll explain how you can pass values to a PowerShell function.
In my previous article, I showed you how to create a function in Windows PowerShell. My original intent had been to end the series
there. After writing that article however, I realized that there were a couple of other important things that I needed to talk about before
ending this series.
One of those things that I still need to cover is the use of parameters. I showed you how to use a function, but the function that I used
in my example was relatively static. In the real world, parameters are often passed to and from functions. Consequently, I want to
spend the remainder of this article talking some more about PowerShell functions.
The other thing that I realized that I never talked about was the link between PowerShell and the .NET Framework. You can use .NET
to do all kinds of cool things in PowerShell, so thats what I plan to talk about in Part 8. So now that I have given you a preview of
where I plan to go with this series, lets get down to business.
As you may recall from the previous article, I created a simple function that checks the value of a variable to see if the number that is
associated with the variable is greater than zero. The actual code that I used is shown below:
Function VarCheck
{
If ($X -GT 0){"Bigger than Zero"}
}
$X=4
VarCheck
$X=0
VarCheck
$X=1
VarCheck
The script sets a variable called $X to 4 and then calls the function VarCheck and checks to see if the variables contents (in this case
4) is bigger than 0. The script then sets the variable to 0, calls the VarCheck function and checks to see if the variables contents (in
this case 0) is greater than 0. Finally, the script sets the variables contents to 1, calls the VarCheck function, and checks to see if the
variables contents (in this case 1) is greater than 0. You can see the scripts output in Figure A below.

Figure A: This is the output from my previously created PowerShell script.


So as you can see, the script works exactly as it is supposed to. When I wrote this script however, I wrote it in a way that I hoped
would illustrate how to call a function, without being confusing in the process. In fact, the script represents the simplest way to use a
function. Within the script I have created a named function called VarCheck and any time that I need to call the function I simply treat
VarCheck as if it were a native command.
The method that I used gets the job done, but this isnt the way that PowerShell functions usually work. As you saw in the script, I
would declare a variable and then call the function. More often however, PowerShell scripts simply pass a value to a function rather
than trying to use a variable that has been declared elsewhere (although the two methods can be combined). Let me show you how it
works.

Lets pretend that I need for my script to do the same thing that it does now, but that for whatever reason I want to pass values directly
to my function rather than making use of a variable. If that is the goal then the function would need to be modified to look like the block
of code shown below:
Function VarCheck($arg1)
{
If ($arg1 -GT 0){echo $arg1 " is bigger than zero"}
}
VarCheck 4
VarCheck 0
VarCheck 1
This script pretty much does the same thing as the script that we created before, but there are two differences. The first difference is
that now we are passing values to the function rather than declaring variables within the main body of code. The other difference is
that I have changed the output slightly as a way of making the output more clear.
With that said, lets step through the code and see how this script works. My first line of code defines a named function. Just like
before, I am calling this function VarCheck. The thing that is different from my previous script is that the function name (in this case
VarCheck) is followed by: ($Arg1)
This is how we tell PowerShell that we are going to be passing a parameter (sometimes called an argument, hence the Arg1 name) to
the function. Now if you look closely, you will notice that $Arg1 is a variable because its first character is a dollar sign. This variable
automatically inherits whatever value is passed to the function. Therefore, if we passed a value of 4 to the function then $arg1 would
contain a value of 4.
The second and fourth lines of code contain a set of braces ({}). Remember, the code block that is associated with a PowerShell
function is always enclosed in braces. These braces define the beginning and the end of the functions code.
This particular function only uses a single line of code. Its the line that appears between the two braces. This line if very similar to
what we were using in the original function, but there are two changes. To more clearly illustrate those changes, let me show you both
the old and the new version of this line of code:
This is how the line originally looked:
If ($X -GT 0){"Bigger than Zero"}
This is how the line looks now:
If ($arg1 -GT 0){echo $arg1 " is bigger than zero"}
In both cases the line of code is checking a variable to see if it is greater than (-GT) zero. In the original version, the code checked the
value of $X. As you will recall however, our new script doesnt use the $X variable. We are passing values directly to the function and
the function assigns those values to the variable $arg1. Therefore, the new function compares $arg1 to 0 rather than comparing $X to
zero.
In both lines of code, we are essentially performing an if then. Both lines of code begin with an if and then establish a condition. The
condition is enclosed in parenthesis and in each case compares the value of a variable against 0. The next part of the line is the
then. This is the portion of code that is enclosed in braces. Its what happens if the condition is true.
In our original code, the then portion of the line simply displayed the text Bigger than Zero. In the new version of the code, I have
made a slight modification that displays the value of the $arg1 variable before displaying the Bigger than Zero text. I did this by using
the word Echo, followed by the variable name. If you have ever done DOS batch programming, you may recall that Echo is a
command used to display a line of text.
Now look below the function. You can see that all of my function calls are followed by a value. For example, VarCheck 4 passes the
value of 4 to the function, where it is compared against zero. Although I am passing raw data to the function, you can use the same
technique to pass a variables contents to a function. You can see the output of my script in Figure B.

Figure B: This is the output from my script.


Advertisement

Conclusion
In this article, I have explained how you can pass values to a PowerShell function. In my next article, I want to show you how you can
use PowerShell to tap into the power of .NET.

PowerShell Essentials (Part 8)


by Brien M. Posey [Published on 31 March 2015 / Last Updated on 31 March 2015]
This article continues the PowerShell essentials series by examining the capabilities and limitations of the PowerShell environment.
So far in this article series, I have shown you how to do all sorts of cool things using Windows PowerShell. As I sat down to write this
article however, it occurred to me that I had never taken the time to talk about PowerShells capabilities and limitations.
In recent years, Microsoft has had a big problem with lack of consistency. Lets take Windows 8 for example. There are actually four
completely separate Windows 8 platforms PC, Windows Phone, Windows RT, and Xbox One. The really crazy thing is that these
various Windows platforms are not compatible with one another. Each has its own app store and the apps that you download from one
app store are not compatible with other device types. You cant for instance run a PC app on Xbox One.
You might have heard a lot recently about Windows 10 and universal apps. Universal apps are Microsofts attempt at cleaning up the
mess that has been brought about by platform inconsistency. Supposedly universal apps will be able to run on any Windows 10 device
regardless of whether it is a PC, tablet, phone, or whatever.
So what could all of this possibly have to do with PowerShell? Well, Microsoft has had similar struggles when it comes to the
command line. Earlier versions of PowerShell were extremely limited. There were relatively few cmdlets available, plus there were
multiple command line interfaces to choose from. More recent versions of PowerShell are much more powerful. The current version of
PowerShell supports thousands of native cmdlets, add-on cmdlets (that can be imported through modules), and legacy commands
from other environments.
So what are these legacy commands? Well, they come in two different forms. The first legacy command type could best be described
as DOS commands. I grew up during the 80s and back then if you had a PC you were using something called Disk Operating System,
or DOS. The DOS environment included numerous native commands and even had its own scripting language that was often referred
to as batch programming.
Most of the earlier versions of Windows were graphical platforms that ran on top of DOS. Modern Windows operating systems are true
operating systems that are based on the NT Kernel instead of on DOS. Even so, even the newest Windows versions include a
Command Prompt window that fully supports DOS commands that were first brought about over 30 years ago.
Early versions of PowerShell adopted a few DOS commands, such as CLS, which clears the screen. To say that these versions of
PowerShell fully supported DOS commands however, would have been completely inaccurate. Most DOS commands were not
supported.
Newer versions of PowerShell include support for the vast majority of the DOS commands that I have tried using. Although some
sources indicate that PowerShell fully supports all of the same commands as the Windows Command Prompt however, it doesnt
actually support all of them. PowerShell supports most of the DOS commands that you are likely to use on a regular basis. Its mostly
the more obscure commands that are missing.
So what commands are missing? I honestly dont know. I have never seen a comprehensive list outlining supported and unsupported
commands. Even so, I can give you an example of a missing command.
There was a time when DOS did not include a text editor. Back then if you wanted to create a text file, batch file, or whatever you had
to enter the following command:

COPY CON <your filename>


After entering this command you could type the files contents and then press Ctrl+C. This would create a file using the name that you
specified. As you can see in Figure A, this method still works using the Windows Command Prompt environment.

Figure A: The COPY CON command works in the Windows Command Prompt window.
Now check out Figure B and you will see what happens if you try the same thing in PowerShell.

Figure B: The COPY CON command does not work in PowerShell.


So is this a big problem? Probably not. Almost nobody uses COPY CON anymore. As I said before, PowerShell supports most of the
old DOS commands that you are likely to need, but it doesnt support every DOS command.
Earlier I mentioned that there was another type of legacy command that is supported within PowerShell. I dont really know what to call
these commands, so I will call them legacy Windows commands. As previously mentioned, DOS had its own command set. Later,
versions of Windows such as Windows 95 and Windows XP introduced some new commands that werent a part of the original DOS
command set. These new commands were used within the Command Prompt window.
The current version of PowerShell seems to fully support these newer commands. One example of such a command is Net. The Net
command can be used for a lot of different things. Suppose that you wanted to view your computers drive mappings. To do so, you
could use the NET USE command, which you can see in Figure C. You can even use NET USE to create new drive letter mappings.

Figure C: PowerShell supports the Net command.


Of course Net is only one example of command line environment commands that are supported through PowerShell. All of the
extended command set commands that I have tried to use have worked through PowerShell.
As you can see, PowerShell is far more capable than it has ever been in the past. Even so, PowerShell does have its limits.
PowerShell cmdlets do not exist for every conceivable purpose. Luckily, PowerShell is extensible. In fact, there are three different
ways to extend PowerShells capabilities.
The first method involves writing your own cmdlets. This topic is beyond the scope of this article series (maybe I will cover it in a future
series if there is enough interest), but Microsoft gives you all of the tools that you need to create PowerShell cmdlets to do whatever
you want.
The second way that PowerShell is extensible is through the use of modules. Modules are essentially collections of non-native
cmdlets. You can import a module into PowerShell by using the Import-Module command. There are dozens of modules available for
download both from Microsoft and from third party sources. For example, you might use a module to extend PowerShell so that you
can use it to manage Microsoft Azure.
The third way in which PowerShell is extensible is the most powerful of all. As I briefly mentioned in my previous article, PowerShell
can take advantage of .NET. The .NET environment makes it possible to do things that PowerShell isnt capable of doing on its own.
For instance, if you want to do advanced math through PowerShell then you can do so by leveraging the power of .NET.

Conclusion
I had originally planned on discussing .NET in this article, but will cover it in Part 9 instead. For those of you who are not developers,
let me assure you that leveraging the .NET environment through PowerShell is surprisingly easy to do. I will show you how in my next
article.

PowerShell Essentials (Part 9)


Published on 28 April 2015 / Last Updated on 28 April 2015]
This article continues the discussion of PowerShell by talking about how to leverage the power of .NET.
When I wrapped up my previous article in this series, I mentioned that one of the most powerful ways to unlock the true potential of
PowerShell is to delve into .NET. Traditionally, .NET has been the domain of developers and is something that system administrators
rarely, if ever have to touch. Even so, it is worth learning a little bit about .NET because doing so will make a dramatic difference in
what you can do with PowerShell.
Before I get started, let me clarify that I am not a professional developer. Dont get me wrong. I can write code. Its just that I dont do
development for a living and most of the code that I have written probably violates a number of established best practices. I know how
to get the job done, but my code usually isnt pretty.
The reason why I am telling you this is to reassure you that I am not about to jump straight into the proverbial abyss, and assume that
you know all about .NET development. On the contrary. I am going to give you a really quick crash course in .NET and then I will show
you how to use PowerShell to exploit what I have just shown you. Please believe me when I say that this is going to be a lot easier
than it sounds. So with that said, lets get started.
As you learned at the beginning of this article series, PowerShell cmdlets are made up of verb-noun combinations. Because verbs and
nouns are able to be used in various combinations, you end up with groups of PowerShell cmdlets that perform similar tasks.

To show you what I mean, take a look at Figure A. In this figure, I entered the Get-Command cmdlet, followed by *-VM. This caused
PowerShell to list all of the cmdlets that are based on the VM noun. These are all cmdlets that are used for working with Hyper-V
virtual machines. In other words, there is a group of cmdlets that provide virtual machine functionality.

Figure A: All of these cmdlets are related to virtual machines.


Conveniently, .NET is organized in a somewhat similar way. The difference is that the organizational structure is a bit more formal and
the terminology is different.
If you look back at Figure A, you will see a number of PowerShell cmdlets that are each related to Hyper-V virtual machines. Even
though these cmdlets are loosely related to one another, there is no formal grouping beyond the default module.
In .NET we dont really have cmdlets per se. Instead, we have classes. A class is defined as an individual unit of functionality. If we
were to continue to use virtual machines as an example, there might be a class for creating a virtual machine, a class for starting a
virtual machine, and a class for renaming a virtual machine (these arent real classes, I am only using them as an example). In other
words, each class is capable of performing one specific task.
Classes that are related to one another are grouped into a .NET structure called an assembly. You can think of an assembly as being
similar to a PowerShell module. In PowerShell, a module is a collection of cmdlets. In .NET, an assembly is a collection of classes.
Another structural component that I need to quickly mention is a namespace. I will be the first to admit that namespaces can be
complicated. When it comes to accessing .NET assemblies through PowerShell however, you can usually think of a namespace as a
label that allows multiple classes to be used, even if those classes belong to different assemblies.
To make this a bit clearer, think about what happens when you need to use PowerShell modules. You may need to initially import the
modules, but once the modules are imported you are free to use the cmdlets within those modules without addressing the module by
name. The .NET namespaces work in a similar way. They allow you to use multiple assemblies without having to always reference
which assembly contains which class.
One last piece of the puzzle that I need to mention is the method. Although its not technically precise, you can loosely think of a
method as an individual .NET command. A .NET class can contain one or more methods.
So now that I have talked about the basic structure used by .NET, lets talk about some syntax. Remember earlier when I said that
.NET namespaces could apply to classes from multiple assemblies. The reason for that is that Windows includes something called the
System Namespace which is a huge collection of classes. You can see the contents of the .NET system namespace here.
As you look through the list of classes, you will quickly realize that some are useful only to developers, but others could be useful in
PowerShell environments. If you find a class that you want to use, the first thing that you will probably want to do is to determine which
methods make up the class. To do so, you can use the following command:
[<class name>].Get-Methods() | Select-Object Name Unique

This command displays the names of all of the methods within the class that you specify. The Unique switch gets rid of the
duplicates. To give you a more concrete example, lets take a look at the methods that exist for the Random class. The command for
doing so is:
[Random].GetMethods() | Select-Object Name Unique
You can see the list of available methods shown in Figure B.

Figure B: There are seven unique methods to the Random class.


Its actually pretty easy to use the methods that are displayed. At its simplest, you will need to enter the class name (in brackets),
followed by two colons, and the method name. Let me give you an example.
Pretend for a moment that for whatever reason, you needed your PowerShell script to calculate the value of PI. Well, it just so
happens that there is a PowerShell class called Math and it has a method called PI. Therefore, you could get the value of PI by
entering:
[Math]::PI
You can see what this looks like in Figure C.

Figure C: You can use PowerShell to return the value of PI.


OK, by now you have probably noticed that I started out talking about the class named Random, but when I wanted to show you how
to use a class and a method I used the Math class instead of the Random class. There is a method to my madness.
As you will recall, I promised to keep the .NET lesson as simple as I could. I couldnt think of an easier example than calculating PI.
Now that you know the basic syntax for using .NET methods we can look at using some other methods.

Conclusion
In this article, I have shown you the basics of using .NET methods within PowerShell. In my next article, I will show you how to use the
Random method. In doing so, I will also show you how you can use MSDN to get help with a methods syntax.

PowerShell Essentials (Part 10)


by Brien M. Posey [Published on 28 May 2015 / Last Updated on 28 May 2015]

This article concludes the PowerShell for Beginners series by talking more about PowerShell and .NET
In my previous article, I began talking about how you can use PowerShell to tap into the power of .NET. Along the way, I showed you
a couple of examples such as how to calculate the value of PI. In this article, I want to talk some more about your options for
interacting with .NET.
As I explained in the previous article, interacting with .NET requires you to know about classes and methods. A class is basically a
category of commands and a method can be thought of as an individual command. I am simplifying things, but for right now this is a
safe way of thinking about classes and methods. If you think back to my PI example, the class was called Math. The Math class
contains all of the math related functions (or methods). PI was the name of a method within the Math class. Using the PI method
required us to specify the class name (Math) and the method name (PI). The actual command looks like this:
[Math]::PI
As I hinted in the previous article, things arent always quite that simple. The nice thing about the PI method is that we were able to
use it as a standalone object. We didnt have to provide any additional information. Using other classes and methods isnt always quite
so simple.
For the sake of discussion, I want to use the Random class to show you how to interact with methods. You got a taste of this class in
the previous article when I explained that you could list the methods that exist within the Random class by using this command:
[Random].GetMethods() | Select-Object Name Unique
There are seven unique methods to the Random class including Next, NextDouble, NextBytes, ToString, Equals, GetHashCode, and
GetType. But how do you use these methods? Clearly, this isnt going to be as simple as displaying the value of PI.
I could jump right in and tell you exactly how to use the Random class and its corresponding methods, but I think that I would be doing
you a disservice if I did. The reason for this is that Random is only one of many different classes that are available through .NET. It
wouldnt be practical for me to write about every class and every method. Likewise, it would not be realistic for me to expect you to
memorize the syntax for every method in existence. So rather than just showing you how to use the Random class and its methods, I
would rather show you what to do in a real life situation when you are faced with a class or a method that you do not know how to use.
In this type of situation, I recommend turning to MSDN. If you are not familiar with MSDN, it is the Microsoft Developer Network and is
accessible at http://msdn.microsoft.com. MSDN is Microsofts go-to reference for developers and it contains all of the information that
you will ever need about .NET and about PowerShell.
In my opinion, navigating MSDN directly can be a little bit cumbersome. Its a lot easier to do a Web search on a phrase like .NET
random class. The first result will usually be an MSDN document. If you look at Figure A for instance, you will see an MSDN
document related to the Random class. This document shows you class syntax for a variety of programming languages. Unfortunately,
PowerShell isnt among the languages listed, but that isnt a problem.

Figure A: MSDN contains full documentation for .NET classes.

If you look at the very bottom of the figure above, you will notice that there is a section called Methods. The Methods section lists the
methods that are associated with the .NET class. You can click on an individual method to learn more about it. If you click on the Next
method for instance, you will see that it is designed to return a positive random integer.
Admittedly, the information on MSDN can be a little bit tough to follow if you are not a developer, so let me break it down for you. Like
the Math class, if you want to use the Random class, you will have to enclose the class name in brackets. This holds true for any .NET
class.
If you simply enter [Random] into PowerShell, you get a little bit of information about the Random class. As you can see in Figure B,
we can see that the class is public, and that it is serial. We can also tell that the Random class is a system object.

Figure B: Entering [Random] produces a bit of information about the Random class.
Another thing that we can tell right away is that you cant just enter [Random] to get a random number. This is to be expected. After all,
Random is a class name, not a function. Entering [Random] and expecting to get a random number would be like entering [Math] and
expecting to see the value for PI. Its not going to happen. To put it another way, a class is nothing but a classification. Its the methods
that do all of the work.
If you want to produce a random number, you will need to use the Next method. The basic syntax used for doing so is a little bit
different from what you might be used to. The command used to generate a random number looks like this:
([Random]1).next()
In this command, the Random class is using the number 1 as a starting value and calling the Next method, which produces a random
number. The starting value is called a seed value. It is used when you want to generate a predictable random number (for testing
purposes). You can use any seed value you want.
Remember when I said that the Next method produces a 32-bit positive integer. A 32-bit positive integer is a relatively large number. If
you use 1 for the seed value then the resulting random number is 534011718. If you want to have a bit more control over the output,
you can use a command like this one to specify the output range. This command picks a random number between 1 and 100:
([Random]1).next(1,100)
Again, if you use a seed value then the command will produce identical results each time it is run.
One last thing that I want to mention is that just because I used the Random class to explain how to get help using classes and
methods, does not mean that you have to use [Random] to generate a random number. Often times Microsoft has created PowerShell
cmdlets that leverage .NET so that you do not have to do so manually. For example, there is a PowerShell cmdlet called Get-Random
that retrieves a random number. If you wanted to generate a random number between 1 and 100, you could use this command:
Get-Random Maximum 100 Minimum 1
This command does not use a seed value and the results are therefore not identical.

Conclusion
In this article series, I have shown you the basics of working with Microsoft PowerShell. As you have seen, PowerShell gives you
almost total control over the Windows operating system.

Potrebbero piacerti anche