Windows PowerShell's Syntax
Introduction to PowerShell's SyntaxThe fact that you
almost don't need this page is a testament to the intuitive nature of PowerShell. Yet for those who wish to save time fumbling with the
PowerShell syntax, it may pay to have a refresher of these rules of
scripting grammar. Windows PowerShell Syntax Topics
♣
PowerShell is fundamentally case insensitive.
Every object and every cmdlet is case insensitive. Set-Location
performs exactly the same action as set-location. However, where your data has case sensitive values, there are PowerShell operators to deal with
'case'. For example, -gt means greater than, -match means
contains a particular string value. Now you can force these and similar operators to be case sensitive by prefixing with a 'c'. -cmatch, or -cgt mean that the comparison will be case sensitive.
For many years a bad attitude to syntax hindered me. My
breakthrough was realizing that punctuation marks are there to aid the
readers' understanding; my mistake was thinking syntax rules were designed
by my English teacher as a way of finding new ways to tell me off.
With PowerShell's syntax the comma is frequently used to separate items on a list.
Whereas the semi-colon is to split separate ideas. Let us study this
example:
Clear-host $i=0 $Log = Get-EventLog -list ForEach ($Item in
$Log) { "{0,-30} {1,-20} {2,13}" -f ` $Item.Log, $Item.OverflowAction,
$Item.MaximumKilobytes }
Note 1: Each $Item is separated by a comma. No
sign of the semi-colon, yet.
Note 2: The comma is also used so separate items in an
array {0,-30}
Suppose we want to count the number of eventlogs. Let us introduce
a variable $i
Clear-host $i=0 $Log = Get-EventLog -list ForEach ($Item in
$Log) { "{0,-30} {1,-20} {2,13}" -f ` $Item.Log, $Item.OverflowAction,
$Item.MaximumKilobytes; $i++ } "There are $i eventlogs"
Note 1: The counter variable, $i++ is new element, which
is not connected to the list; time for a semi-colon before the counter
variable.
= Equals
and ! Not equalThe equals sign (=) behaves just as expected. As usual,
'=' tests for equivalence, or sets a variable to be equal to a certain value.
The equals sign has a counterpart ! (Exclamation
mark) meaning, 'not equal'. You may also employ -not instead of ! I just include these
two basic operators, '=' and ! for completeness.
Some people call this symbol (-) minus, others a refer to this sign as a dash, I mostly call it a hyphen. Let me be clear, this character maps to ASCII 45, to see the character, hold down ALT key, type 45 on numeric keypad, now let go of ALT key. PowerShell uses this - symbol for two
purposes. Firstly, to join verb-Noun pairs, for example out-File guy.txt. Secondly, this minus sign is also used for
parameters, modifiers, or filters such as -list; as in Get-Eventlog -list. The
trap I fall into is to put a space between the minus and the modifier. get -eventlog is clearly wrong,
because there is a space between get and -. The correct format is, Get-Eventlog,
with no space.
Guy
Recommends: WMI Monitor and It's Free!
Windows Management Instrumentation (WMI) is one of the hidden
treasures of Microsoft operating systems. Fortunately, SolarWinds
have created a
Free WMI Monitor so that you can discover these gems of performance
information, and thus improve your PowerShell scripts. Take the guess work out of which WMI counters to use when scripting the
operating system, Active Directory or Exchange Server.
Download your free copy of WMI Monitor
The ability to pipe the output of one command, so that it becomes the input
of the second command is PowerShell's signature tune. Thus it is
important to be clear about this | symbol.
When typed in notepad, the pipeline symbol looks like this: | but when typed in the Microsoft Shell
it looks like ¦. On my keyboard the key I am using this symbol is next to the z, however I have seen keyboards where the
pipeline key is next
to numeric 1 on the top row. Once you find, then type the key, you get a pipe symbol
(|). To be crystal clear this pipeline symbol corresponds to ASCII 124. N.B this not ASCI 0166.
Test by holding down the Alt key and typing the number (124 or 0166) on the numeric pad, then letting go of the Alt key.
In PowerShell syntax the pipeline symbol (|) has three roles.
- Think of the pipeline as a method for joining two commands.
Get-Eventlog system |
Format-List You could even have two pipelines in one statement. - PowerShell deploys Pipeline to introduce
a 'Where' clause.
Get-Eventlog security |where {$_.Eventid -eq "540"}
-
Pipeline is similar to 'more' in DOS
Get-Eventlog system | more
...
See more about $_.
PowerShell's brackets surprised me. Each type has a specific role, the wrong bracket will cause an otherwise sound command, to fail miserably. The message is
clear, you have to
understand your brackets. Each of these (), {} or [] has a different purpose.
After a while, PowerShell's syntax becomes your friend in producing
error-free code. For instance, if you need a script block, always
associate the task with the {Braces style of bracket}. 1) () Parenthesis or Curved brackets are
used for required options in the foreach loop Example: $disk= WmiObject Win32_LogicalDisk "Drive Letter Size GB " foreach
($drive in $disk ) {"Drive = " + $drive.Name} 2) {} Braces or 'curly' brackets are required for
block expressions within a command, for instance, the 'where' or 'where-object' command. Example: Get-Service | where {$_.status -eq "stopped" } 3) [] Square brackets are used for optional elements, for example, to filter services beginning with 's': Example: Get-Service [s]* I have also found
square brackets are needed for math functions such as [int]value Example: [int]TotalProcessorTime 4) > and >> work as with DOS and cmd, they output the results of your commands
not to screen, but to a text file. The double chevron >> appends, the single > will overwrite any existing data in the file. Conclusion, the type of bracket really matters, therefore always double check before you select {} () or [].
See more about PowerShell's brackets.
|