PowerShell Variables

Variables in PowerShell is used in almost every script, if not all of them. Variables allows us to save information that we can use later on in our script.

To save a value in a variable, we simply type:

$Number = 32

Then, when we type $Number in PowerShell, the following will be shown.

1

 

In the same way, we can save text in a variable, a String, by typing the following:

$String = "This is just a line of text"

2

When we save text in a string, it is important that we enclose the text with “”. If we do not do this, we will get an error similar to this one:

3

When using variables, PowerShell will automatically select the best object type for you. In our first example, PowerShell will automatically create an object of the type “Int32”, where as in the second example it will create a “String”.

So far this is great if we know the value that we will use later on, or if it always is the same, but what if we need a script that uses today’s date for example?

By using the CmdLet “Get-Date”, we can save today’s date in a variable.

$Date = Get-Date

When we type $Date we will see the following:

4

By default, PowerShell will select the “long date” format, which might be useful in some scenarios, but to long in others.

To see what we can do with a variable, we can type the following command:

$Date | Get-Member

This will show us a list of available methods and properties that we can use on the object. As you can see in the list, we have a “Method” called “ToShortDateString”. To use this method, simply type:

$Date.ToShortDateString()

The result will be the following:

5

This is the very basics of using variables and in my other guides I will show you more on how these are used.

As a side note;
To get a complete list of available CmdLets and Functions, simply type the following in PowerShell:

Get-Command

As you can see, the list that is returned is quite long and gives you a hint in what is possible to do without having to write a seven pages long script.

Back to the list of PowerShell Guides

This entry was posted in Powershell and tagged , , . Bookmark the permalink.

1 Response to PowerShell Variables

  1. Pingback: PowerShell Guides - A guide to Microsoft ProductsA guide to Microsoft Products

Leave a Reply

Your email address will not be published. Required fields are marked *