Microsoft PowerShell's SyntaxIntroduction 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. Topics for PowerShell Syntax
Case InsensitivePowerShell 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. Comma and Semi-colonFor 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 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 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. Hyphen -dash -minusSome 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. Pipeline, the Pipe Symbol | (Sometimes looks like ¦)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.
PowerShell's BracketsPowerShell'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 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 []. Double and Single QuotesAs with brackets, the type of quotation mark is highly significant in PowerShell syntax. Here is an example to illustrate the differences between single quotes and double quotes in PowerShell $Bill = 57 "My total is $Total" Using the double quotes illustrates PowerShell's intelligence, it
realizes that $Total is variable holding the value 64, thus the output is: However, if we substitute single quotes: 'My total is $Total', we get a different, literal answer: My total is $Total. PowerShell assumed that for a reason best known to us, we did not want it to use the math representation. + Plus as a ConcatenatorWhen I wanted to join text and numbers, I spent time looking for PowerShell's concatenator. Silly me, all
I need is the simple + plus sign. This is because in PowerShell +
joins text strings as well as its traditional job of adding numbers. For example: Achieve Word-wrap with
Backtick`
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Operator |
Definition |
| # | # The hash key is for comments |
| + | Add |
| - | Subtract |
| * | Multiply |
| / | Divide |
| % | Modulus (Some call it Modulo) - Means remainder 17 % 5 = 2 Remainder |
| = | equal |
| -not | logical not equal |
| ! | logical not equal |
| -band | binary and |
| -bor | binary or |
| -bnot | binary not |
| -replace | Replace (e.g. "abcde" –replace "b","B") (case insensitive) |
| -ireplace | Case-insensitive replace (e.g. "abcde" –ireplace "B","3") |
| -creplace | Case-sensitive replace (e.g. "abcde" –creplace "B","3") |
| -and | AND (e.g. ($a -ge 5 -AND $a -le 15) ) |
| -or | OR (e.g. ($a –eq "A" –OR $a –eq "B") ) |
| -is | IS type (e.g. $a -is [int] ) |
| -isnot | IS not type (e.g. $a -isnot [int] ) |
| -as | convert to type (e.g. 1 -as [string] treats 1 as a string ) |
| .. | Range operator (e.g. foreach ($i in 1..10) {$i } ) |
| & | call operator (e.g. $a = "Get-ChildItem" &$a executes Get-ChildItem) |
| . (dot followed by a space) | call operator (e.g. $a = "Get-ChildItem" . $a executes Get-ChildItem in the current scope) |
| . |
.Period or .full stop for an objects properties $CompSys.TotalPhysicalMemory |
| -F | Format operator (e.g. foreach ($p in Get-Process) { "{0,-15} has {1,6} handles" –F $p.processname,$p.Handlecount } ) |
| Operator |
Definition |
| -lt | Less than |
| -le | Less than or equal to |
| -gt | Greater than |
| -ge | Greater than or equal to |
| -eq | Equal to |
| -ne | Not Equal to |
| -contains |
Determine elements in a group. This always returns Boolean $True or $False. |
| -notcontains |
Determine excluded elements in a group This always returns Boolean $True or $False. |
| -like | Like - uses wildcards for pattern matching |
| -notlike | Not Like - uses wildcards for pattern matching |
| -match | Match - uses regular expressions for pattern matching |
| -notmatch | Not Match - uses regular expressions for pattern matching |
| Bitwise | |
| -band | Bitwise AND |
| -bor | Bitwise OR |
| -is | Is of Type |
| -isnot | Is not of Type |
| Other Operators | |
| if(condition) | If condition |
| elseIf(condition) | ElseIF |
| else(condition) | Else |
| > |
Redirect, for example, output to text file Example .\cmdlet > stuff.txt |
| >> | Same as Redirect except it appends to an existing file |
Every language must have its grammar rules. However, with PowerShell syntax the rules for brackets, quotation marks and commas, all seem logical and straightforward.
• PowerShell Home • Syntax • -f format • Pipeline • Quotes • Format-table • Group • Select-String
Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
Download my ebook:
|
*
|
|
Guy Recommends: SolarWinds Exchange Monitor
|
|
Home Copyright © 1999-2008 Computer Performance LTD All rights reserved Please report a broken link, or an error. | |