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.
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"
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:
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:
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:
The result will be the following:
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:
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.
Pingback: PowerShell Guides - A guide to Microsoft ProductsA guide to Microsoft Products