Let's get a few syntax basics down. This section is not meant to be an exhaustive tutorial on PowerShell's syntax but should serve as a good, brief introduction.
Let's walk through the following script:
Even if you are not very familiar with PowerShell yet, you may already be able to tell what the preceding script is trying to accomplish. Simply put, the script iterates over the listed servers and saves the list of running services into a file that acts as a timestamp.
This line creates a variable called $currdate
that gets the current system date in the "yyyyMMdd hhmmtt"
format:
The snippet with an at (@
) sign, @("ROGUE", "CEREBRO")
, creates an array, which is then stored in another variable called $servers
:
Since $servers
contains multiple values, when you pipe it to the Foreach-Object
cmdlet, each value is fed into the script block inside Foreach-Object
:
You are also introduced to a few concepts inside the Foreach-Object
block.
To get the current pipeline object, you can use $_
. The $_
, also referred to as $PSItem
, is a special variable. It is part of what PowerShell calls automatic variables. This variable only exists and can only be used in the content of a pipeline. The $_
variable contains the current object in the pipeline, allowing you to perform specific actions on it during the iteration:
A backtick is an escape character, for example, to add a newline. It is also a line continuation character:
Note that the strings are enclosed in double quotes:
Strings in PowerShell can also be enclosed in single quotes. However, if you have variables you want to be evaluated within the string, as in the preceding example, you will have to use double quotes. Single quotes will simply output the variable name verbatim.
PowerShell has a subexpression operator, $()
. This allows you to embed another variable or expression inside a string in double quotes, and PowerShell will still extract the variable value or evaluate the expression:
Here is another example that demonstrates when subexpressions will be useful. The expression to get the date that is 10 days from today is as follows:
If we want to display the value this expression returns, you may be tempted to use:
However, this simply redisplays the expression; it doesn't evaluate it. One way to get around this without using a subexpression would be to create a new variable and then use it in the double-quoted string:
With the subexpression, you don't need to create the new variable:
The example we walked through should give you a taste of simple scripting in PowerShell.
The following is a table that outlines some of these common scripting components and operators:
The table is not a comprehensive list of operators or syntax about PowerShell. As you learn more about PowerShell, you will find a lot of additional components and different variations from what has been presented here.