{"id":2094,"date":"2015-09-30T00:00:00","date_gmt":"2015-09-30T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/the-complete-guide-to-powershell-punctuation\/"},"modified":"2017-01-20T15:49:21","modified_gmt":"2017-01-20T15:49:21","slug":"the-complete-guide-to-powershell-punctuation","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/the-complete-guide-to-powershell-punctuation\/","title":{"rendered":"The Complete Guide to PowerShell Punctuation"},"content":{"rendered":"<div id=\"pretty\">\n<p class=\"start\">PowerShell is both a powerful command-line shell and a scripting language, providing the full richness of the .NET framework in an interactive environment. PowerShell is useful for administrators and developers of varying skill levels. Though it requires effort to learn, you can be quite productive with PowerShell after gaining \u00a0only a small proportion of the skills and then acquiring more incrementally as you need to. Probably the most oft-cited hurdle of getting up to speed with PowerShell is learning the syntax and, in particular, the punctuation. If you review articles on PowerShell (mine included) you will often see a reader comment to the effect, &#8220;Good stuff but you don&#8217;t really explain what [X] is&#8230;&#8221; where X might be &#8220;<code>% { ... }<\/code>&#8221; or &#8220;$_&#8221; or &#8220;<code>$($process.name)<\/code>&#8221; or many other quirky-looking expressions. Every writer makes assumptions about what basic information a reader will know coming in, but unfortunately that leaves occasional knowledge gaps leading to the sort of comment I have indicated.<\/p>\n<p><img decoding=\"async\" class=\"float-right\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/2289-imgC6.jpg\" alt=\"2289-imgC6.jpg\" \/><\/p>\n<p>This reference is an attempt to tackle that knowledge gap. Whether you keep it bookmarked, keep it taped to your monitor, or keep it tucked under your pillow, just make sure it is within arm&#8217;s reach the next time you open a new PowerShell article to read, so the lexicon herein will let you translate, or comprehend, whatever the author is throwing at you. If you have a burning need to know what a particular character is doing in an article you are reading now, jump right to the attached wallchart to find out. Otherwise, I encourage you to start with this short introduction that provides just a bit more context than the wallchart allows space for.<\/p>\n<h2>Expressions<\/h2>\n<p>Though sometimes an expression may stand alone (you could just type <code>5 + 3<\/code>, for example, and press return to evaluate that expression), parentheses are often a key element to an expression in PowerShell. The catch is noticing what comes just before: is it just parentheses or is the opening parenthesis preceded by a dollar sign <code>$<\/code> or at-sign <code>@<\/code> ?<\/p>\n<h3><code>(...)<\/code><\/h3>\n<div class=\"indent\">\n<p>Plain parentheses act as a <i> grouping expression<\/i> to encapsulate a single cmdlet or a single sequence, where a sequence might be something piped to something else that is \u00a0piped to something else again. The output of a sequence comes only from the terminal command or cmdlet of the pipeline, i.e. a single source. You could, for example, execute this&#8230;<\/p>\n<pre>(get-process -name win*).name<\/pre>\n<p>to emit the name of all processes with the prefix &#8220;win&#8221;. Without the parentheses, the argument passed as the -name parameter is &#8220;win*.name&#8221;, which is quite different!<\/p>\n<p>An important aspect of a grouping expression is the encapsulation. The content of the expression is executed until completion and the result is then returned to be operated on by something else. Taking advantage of this encapsulation is what allows you to update a file in-place (i.e. without a temporary file or file renaming):<\/p>\n<pre>(Get-Content myStuff.txt) | %{ $_ -replace '0', '00'} | Set-Content myStuff.txt<\/pre>\n<p>(Note that the percent (%) above is just a terse alias for ForEach-Object, PowerShell&#8217;s looping construct.) Without the parentheses, the content of myStuff.txt is fed a bit at a time through the pipeline by Get-Content so that Set-Content attempts to write to the same file that is in the midst of reading, so Set-Content fails.<\/p>\n<\/div>\n<h3><code>$(...)<\/code><\/h3>\n<div class=\"indent\">\n<p>Similar to a grouping expression, this denotes a <i>sub-expression<\/i>. A sub-expression may encapsulate <i>multiple<\/i> commands or command sequences, separated by semicolons. Each sequence contributes to the output of the sub-expression.<\/p>\n<pre>$($x=1;$y=2;$x;$y)<\/pre>\n<p>In practice, though, sub-expressions are most useful inside a string literal; you rarely need them otherwise.\u00a0 Inside a double-quoted string, you can interpolate simple variables simply by naming them, e.g.<\/p>\n<pre>\"my name is $name\"<\/pre>\n<p>But for interpolating the property of an object, you must wrap it in a sub-expression:<\/p>\n<pre>$p = ps | select -first 1 \r\n\"proc name is $($p.name)\"\r\n<\/pre>\n<\/div>\n<h3><code>@(...)<\/code><\/h3>\n<div class=\"indent\">\n<p>With the at-sign, you have an <i>array expression<\/i>. Essentially the same as a sub-expression, except this guarantees to return an array. That little difference makes this notation very useful and very commonly used. Consider a cmdlet that returns a collection of a certain type, say X. If two or more objects are returned in a given call, they are returned as an array of type X.<\/p>\n<p>If, on the other hand, only one object is being returned, you just get that object, an X. Wrapping the call in an array expression forces it to always be an array so you do not have to worry about edge cases for one value or no values, e.g.<\/p>\n<pre>$a = @(ps | where name -like 'foo') <\/pre>\n<\/div>\n<h2>Statements<\/h2>\n<p>Statements work together with expressions to provide the backbone components of PowerShell. Generally, a statement specifies an action to be performed <i>without<\/i> necessarily returning a value, whereas an expression performs some action that is <i>designed<\/i> to return a value. Interestingly, it is hard to say which is a &#8220;larger&#8221; component: expressions can be components of statements, and statements can be components of expressions.<\/p>\n<p>There are several key symbols related to statements. As in many programming languages, you can group statements into a block to be treated as if it were a single statement. Use braces for this, i.e. <code>{<\/code> and <code>}<\/code>.<\/p>\n<p>A statement terminates typically at the end of a line-where you have a line break-but if you want to put multiple statements on one line, you can use the other statement terminator, a semicolon (<code>;<\/code>). Alternatively, if you want to split a single statement across multiple lines you can do that with a line break as well-but only at places in the statement where PowerShell knows there is more to come. At other points, you have to explicitly tell PowerShell that there is more by using a backtick, or grave accent (<code>`<\/code>) as the very last character on a line. (A backtick is PowerShell&#8217;s escape character, so what you are doing is escaping the normal meaning of the immediately following line break.)<\/p>\n<p>If, on the other hand, you want to chain statements together (i.e. if the output of one statement is supposed to be the input of the next statement), then use the pipe (<code>|<\/code>) symbol.<\/p>\n<h2>Comments<\/h2>\n<p>Comments in PowerShell, as in many languages, come in two flavors. Run-until-end-of-line comments begin with an octothorp (<code>#<\/code>), while block comments that span multiple lines are bracketed with <code>&lt;#<\/code> and <code>#&gt;<\/code>.<\/p>\n<h2>Variables<\/h2>\n<p>Variables are very simple in PowerShell-except for the complicating, little details. The first simple rule: all variables begin with a dollar sign (<code>$<\/code>). And the first exception: <i>except<\/i> when you want to use a hash table or an array to splat parameters to a function or cmdlet, then your variable starts with an at-sign. (<i>Splatting<\/i> is a technique for passing a dynamic list of parameters to a function; see <a href=\"https:\/\/technet.microsoft.com\/en-us\/library\/jj672955.aspx\"> about_Splatting<\/a>.)<\/p>\n<p>A basic variable may contain only letters, numbers, underscores, and question marks. (Note that <i>letter<\/i> and <i>number<\/i> are in the context of several specific Unicode character classes (Lu, Ll, Lt, Lm, Lo, or Nd), so there are many more characters permitted beyond the 36 standard English ones-18,571 more to be precise!) However, sometimes that&#8217;s just not enough. What if you really want a space in your variable name, or a virgule, or a colon, or&#8230; well, you get the idea. Perhaps the PowerShell team had some spare time to just &#8220;doodle&#8221; with the code base, but they did add support for this. Just enclose your variable name in braces and precede the whole thing, as usual, with a dollar sign. <code>${So this is a valid variable name!}<\/code><\/p>\n<p>This notation is overloaded in a sense (or special-cased, if you prefer) in one very specific scenario. If the &#8220;name&#8221; you specify is a valid <i>drive-qualified path<\/i> (see <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ee126188(v=vs.85).aspx\"> Provider Paths<\/a>) then you can not only <i> retrieve<\/i> that item but also <i>store<\/i> into that item as if it were a variable! An example makes this clear. The table shows conventional syntax on the left, which is exactly equivalent to the variable syntax on the right:<\/p>\n<div>\n<table class=\"MsoTable15Grid5DarkAccent1\">\n<tbody>\n<tr>\n<td valign=\"top\">\n<p><b> \u00a0<\/b><\/p>\n<\/td>\n<td valign=\"top\">\n<p><b> Conventional Notation<\/b><\/p>\n<\/td>\n<td valign=\"top\">\n<p><b> Variable Notation<\/b><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\">\n<p><b> Retrieve<\/b><\/p>\n<\/td>\n<td valign=\"top\">\n<p>$myData = Get-Content C:tmp.txt<\/p>\n<\/td>\n<td valign=\"top\">\n<p>$myData = ${C:tmp.txt}<\/p>\n<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\">\n<p><b> Store<\/b><\/p>\n<\/td>\n<td valign=\"top\">\n<p>1,2,3 | Set-Content C:tmp.txt<\/p>\n<\/td>\n<td valign=\"top\">\n<p>${C:tmp.txt} = 1,2,3<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>Further you can apply addition (really appending) and multiplication (really replicating) to these variables as well! Here&#8217;s a neat example from the PowerShell 3.0 spec itself:<\/p>\n<pre class=\"lang:ps theme:powershell-ise\">${E:tmp\\output.txt} = \"a\"\u00a0  # write text to the given file\r\n${E:tmp\\output.txt} += \"b\" # append text to the file giving ab\r\n${E:tmp\\output.txt} *= 4\u00a0\u00a0 # replicate ab 4 times giving abababab\r\n<\/pre>\n<p>As soon as you go beyond simple scripts, you&#8217;ll need to be aware of scope in PowerShell. Variables are by default defined in <i>local<\/i> scope, meaning they exist only within the confines of the current function or script. But you have several named scopes you may specify (<i>global<\/i>, <i>private<\/i>, and <i>script<\/i> are likely the most common ones you will need). You specify a scoped variable by saying <code>$scope:name<\/code><i> <\/i>as in, for example, <code>$global:myStuff<\/code>.<\/p>\n<p>When a variable contains an object-something beyond a simple value like an integer or a string-you naturally need to be able to refer to components of that object. Use a period to dereference, as in <code>$process.Name<\/code>. That notation even works for hash tables, where instead of a property you specify a key, e.g. <code>$myColorHash.blue<\/code>. Again, though PowerShell is flexible. You can also reference hash items with brackets, so <code>$myColorHash[\"blue\"] <\/code>would return the same value. Finally, arrays use this same bracketed notation, but of course the indexer must be an expression that evaluates to a number.<\/p>\n<h2>Quotes<\/h2>\n<p>Use quotation marks (single or double) to surround string literals in PowerShell, just as you do in many other languages. I would like to say that quoting is so simple in PowerShell that hardly anything needs to be said&#8230; but that&#8217;s not quite the case. In fact, I wrote a whole article about the nitty-gritty details about quoting (see <a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/when-to-quote-in-powershell\/\"> When to Quote in PowerShell<\/a>): But in a nutshell, use double quotes if you want variables and expressions to be interpolated within your literal, and use single quotes if you do not. That applies to both regular strings (<code>\"...\"<\/code> and <code>'...'<\/code>) and here strings (<code>@'...'@<\/code> and <code>@\"...\"@<\/code> ), the latter typically used for multi-line strings.<\/p>\n<h2>Redirects<\/h2>\n<p>PowerShell takes file redirects to the &#8220;nth&#8221; degree (see <a href=\"https:\/\/technet.microsoft.com\/en-us\/library\/hh847746.aspx\"> about_Redirection<\/a>). If you&#8217;ve used DOS shell, you have likely seen a simple file redirect, e.g. <code>dostuff.exe &gt; myfile.log<\/code> to overwrite a file or <code>dostuff.exe &gt;&gt; myfile.log<\/code> to append to a file. With Unix\/Linux you&#8217;ve likely seen that as well as the bit more convoluted <code><\/code> which merges your standard error stream with your standard output stream. PowerShell has those and more, because there are five streams: standard, error, warning, verbose, and debug output streams. You can redirect any of them to a file by number <code>Get-Stuff 4&gt; myfile.log<\/code> or <code>Get-Stuff 4&gt;&gt; myfile.log<\/code>, or you can merge any of them with the standard output:<code><\/code>. PowerShell does <i>not<\/i>, however, have input redirection with a less than (<code>&lt;<\/code>).<\/p>\n<h2>Arithmetic and Assignment<\/h2>\n<p>PowerShell has a typical complement of the four basic arithmetic operators ( <code>+<\/code>,<code> -<\/code>,<code> *<\/code>, and<code> \/<\/code> )plus a modulus operator (<code>%<\/code>). What is particularly handy is that PowerShell also provides compound assignment for all of those ( <code>+=<\/code>,<code> -=<\/code>,<code> *=<\/code>,<code> \/=<\/code>, and<code> %=<\/code> ). That is, <code>a += 5<\/code> is the compound assignment analogous to the <code>a = a + 5<\/code> simple assignment. PowerShell also provides the very typical auto-increment (<code>++<\/code>) and auto-decrement (<code>--<\/code>).<\/p>\n<h2>Summary<\/h2>\n<p>All of the above was just to add a bit of color to the information-dense wallchart just ahead. <a href=\"https:\/\/www.simple-talk.com\/wp-content\/uploads\/2015\/09\/PSPunctuationWallChart_1_0_4.pdf\">Give it a click <\/a>and you&#8217;ll see how every punctuation mark on your keyboard is used (and reused!) in PowerShell. (Well, except for one-see if you can spot it!)<\/p>\n<p><a href=\"https:\/\/www.simple-talk.com\/wp-content\/uploads\/2015\/09\/PSPunctuationWallChart_1_0_4.pdf\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/2289-imgC7.jpg\" alt=\"2289-imgC7.jpg\" \/><\/a><\/p>\n<h2>Afterthought<\/h2>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/2289-psCartoon.jpg\" alt=\"2289-psCartoon.jpg\" \/><\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>It is the punctuation, the strange dollar signs, brackets and parentheses that bewilder anyone learning PowerShell. Add to that the aliases and you can bewilder everyone. The punctuation is essential, so here is the the complete PowerShell wallchart and guide to Powershell Punctuation. PowerShell need no longer be perplexing.&hellip;<\/p>\n","protected":false},"author":221868,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[35],"tags":[4635,4871],"coauthors":[6802],"class_list":["post-2094","post","type-post","status-publish","format-standard","hentry","category-powershell","tag-powershell","tag-sysadmin"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/2094","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/221868"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=2094"}],"version-history":[{"count":8,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/2094\/revisions"}],"predecessor-version":[{"id":69731,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/2094\/revisions\/69731"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=2094"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=2094"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=2094"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=2094"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}