{"id":1787,"date":"2014-04-04T00:00:00","date_gmt":"2014-04-04T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/powershell-one-liners-help-syntax-display-and-files\/"},"modified":"2016-08-04T15:50:01","modified_gmt":"2016-08-04T15:50:01","slug":"powershell-one-liners-help-syntax-display-and-files","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/sysadmin\/powershell\/powershell-one-liners-help-syntax-display-and-files\/","title":{"rendered":"PowerShell One-Liners: Help, Syntax, Display and  Files"},"content":{"rendered":"<div id=\"pretty\">\n<p>This series is in four parts: This is part 1<\/p>\n<ul>\n<li> \t<a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners-help,-syntax,-display-and--files\/\"><b>Part  1<\/b>: Help,  Syntax, Display and Files&#160;<\/a><\/li>\n<li> \t<a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners-variables,-parameters,-properties,-and-objects\/\"><b>Part 2<\/b>: Variables,  Parameters, Properties, and Objects,<\/a><\/li>\n<li> \t<a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners--collections,-hashtables,-arrays-and-strings\/\"> \t<b>Part 3<\/b>:&#160;Collections,  Hashtables, Arrays and Strings<\/a>&#160;<\/li>\n<li> \t<a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners--collections,-hashtables,-arrays-and-strings\/\"> \t<b>Part 4<\/b>:&#160;<\/a><a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners--accessing,-handling-and-writing-data-\/\">Accessing, Handling and Writing Data&#160;<\/a><\/li>\n<\/ul>\n<p class=\"start\">Well, yes, it would be an onerous task indeed to deliver \t<i>everything<\/i>. But per the \t<a href=\"http:\/\/en.wikipedia.org\/wiki\/Pareto_principle\">Pareto principle<\/a>, roughly  \t&#160;eighty percent of what you could want to know about PowerShell is here in this series of articles; possibly  \tmore! &#160;You will tend to learn the other twenty percent \t&#160;as you go, and you may not need &#160;it for  \tquite a ways into your PowerShell explorations. &#160;I feel compelled to confess  \tthat some of the entries are not, strictly speaking, on one physical line, but &#160;are  \twritten in such a way that, if you really want to run them in one line, you can just remove the line breaks and they  \twill work. (Note that that is not generally true of PowerShell syntax.)<\/p>\n<p class=\"MsoNormal\">This series of articles evolved out of my own notes on PowerShell as I poked  \tand prodded it to show me more. As my collection &#160;burgeoned, I began to  \torganize them until I had one-line recipes for most any simple PowerShell task. \t<i>Simple<\/i>, though, does not mean <i> \ttrivial<\/i>. You can do quite a lot in one line of PowerShell, such as grabbing the contents of specific elements of  \ta web page or converting a CSV file into a collection of PowerShell objects.<\/p>\n<p class=\"MsoNormal\">This collection of PowerShell one-liners is organized as follows:<\/p>\n<dl>\n<dt>Part 1<\/dt>\n<dd>  \tbegins by showing you how to have PowerShell itself help you figure out what you need to do to accomplish a task,  \tcovering the help system as well as its handy command-line intellisense. The next sections deal with locations,  \tfiles, and paths: the basic currency of any shell. You are introduced to some basic but key syntactic constructs and  \tthen ways to cast your output in list, table, grid, or chart form.<\/dd>\n<dt><a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners-variables,-parameters,-properties,-and-objects\/\">Part 2<\/a><\/dt>\n<dd>  \tmoves into details on variables, parameters, properties, and objects, providing insight into the richness of the  \tPowerShell programming language. <a href=\"https:\/\/www.simple-talk.com\/sysadmin\/powershell\/powershell-one-liners-variables,-parameters,-properties,-and-objects\/\">Part 2<\/a> is rounded out with a few other vital bits on leveraging the PowerShell  \tenvironment.<\/dd>\n<dt>Part 3<\/dt>\n<dd>  \tcovers the two fundamental data structures of PowerShell: the collection (array) and the hash table (dictionary),  \texamining everything from creating, accessing, iterating, ordering, and selecting. Part 3 also covers converting  \tbetween strings and arrays, and rounds out with techniques for searching, most commonly applicable to files  \t(searching both directory structures as well as file contents).<\/dd>\n<dt>Part 4<\/dt>\n<dd>  \tis your information source for a variety of input and output techniques: reading and writing files; writing the  \tvarious output streams; file housekeeping operations; and various techniques related to CSV, JSON, database,  \tnetwork, and XML.<\/dd>\n<\/dl>\n<p class=\"MsoNormal\">Each part of this series is available as both an online reference here at  \tSimple-Talk.com, <a href=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1966-powershellonelinerswide.html\"> in a wide-form as well<\/a>, and  as a downloadable wallchart (from the link at the bottom of the article) in PDF format for those who prefer a printed copy near at hand.  \tPlease keep in mind though that this is a quick reference, not a tutorial. So while there are a few brief  \tintroductory remarks for each section, there is very little explanation for any given incantation. But do not let  \tthat scare you off-jump in and try things! You should find more than a few &#8220;aha!&#8221; moments ahead of you!<\/p>\n<h2>Notes on using the tables:<\/h2>\n<ul>\n<li>A command will typically use full names of cmdlets but the  \texamples will often use aliases for brevity. Example: Get-Help has aliases <i>man<\/i>  \tand <i>help<\/i>. This has the side benefit of showing you both long and short  \tnames to invoke many commands.<\/li>\n<li>Most tables contain either 3 or 4 columns: a description of an  \taction; the generic command syntax to perform that action; an example invocation of that command; and optionally an  \toutput column showing the result of that example where feasible.<\/li>\n<li>For clarity, embedded newlines (<b>`n<\/b>)  \tand embedded return\/newline combinations (<b>`r`n<\/b>)  \tare highlighted as shown.<\/li>\n<li>Many actions in PowerShell can be performed in more than one way.  \tThe goal here is to show just the simplest which may mean displaying more than one command if they are about equally  \tstraightforward. In such cases the different commands are numbered with square brackets (e.g. &#8220;[1]&#8221;). Multiple  \tcommands generally mean multiple examples, which are similarly numbered.<\/li>\n<li>Most commands will work with PowerShell version 2 and above,  \tthough some require at least version 3. So if you are still running v2 and encounter an issue that is likely your  \tculprit.<\/li>\n<li>The vast majority of commands are built-in, i.e. supplied by  \tMicrosoft. There are a few sprinkled about that require loading an additional module or script, but their usefulness  \tmakes them worth including in this compendium. These &#8220;add-ins&#8221; will be demarcated with angle brackets, e.g. &lt;&lt;pscx&gt;&gt;  \tdenotes the popular PowerShell Community Extensions (<a href=\"http:\/\/pscx.codeplex.com\/\">http:\/\/pscx.codeplex.com\/<\/a>).<\/li>\n<li>There are many links included for further reading; these are  \t\tactive hyperlinks that you may select if you are working online, but the URLs themselves are also explicitly  \t\tprovided (as in the previous bullet) in case you have a paper copy.<\/li>\n<\/ul>\n<div class=\"note\">\n<p class=\"note\"><b>Note:<\/b> Out of necessity, the version of the tables in the articles is somewhat compressed. If you find them hard to read, then there is a wide version of the article <a href=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1966-powershellonelinerswide.html\">available here<\/a>, and a PDF version is available fron the link at the bottom of the article<\/p>\n<\/div>\n<h2>What&#8217;s What and What&#8217;s Where<\/h2>\n<p class=\"MsoNormal\">This is your starting point when you are staring at a PowerShell prompt,  \tknowing not what to do. Find out what commands are available, read help on PowerShell concepts, learn about  \tauto-completion of cmdlets and parameters, see what command an alias refers to, and more.&#160; \tBefore even going to the first entry, though, it is useful to learn one thing: PowerShell has help available  \ton both <i>commands<\/i> and <i>concepts<\/i>. You can look up a command simply with, for example,  \tGet-Help Get-ChildItem (# 1  \tbelow). Or you can search for a command with a substring, e.g.  \tGet-Help file (#3). But as  \twith any programming language you have to know syntax, semantics, structures, &#8230; in short all those conceptual items  \tthat let you work with commands. If you want to know about variables, for example, you have merely to say  \tGet-Help about_variables.  \tAll conceptual topics begin with the &#8220;about_&#8221; prefix (#11).<\/p>\n<p class=\"MsoNormal\">Not at first, but in short order, you will want to be able to find  \tmeta-details about commands as well. By that, I mean to answer questions like: What type of objects does a cmdlet  \treturn? Does a cmdlet have one or multiple sets of parameters available?&#160;  \tWhere does a cmdlet come from? All of those meta-details can be seen from entry 20 below.<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<\/tr>\n<tr>\n<td>Basic help for x<\/td>\n<td>Get-Help cmd (cmd is a full name)<\/td>\n<td>help Get-ChildItem<\/td>\n<\/tr>\n<tr>\n<td>Help in separate window<\/td>\n<td>Show-Command cmd; then select the help icon<\/td>\n<td>Show-Command Get-ChildItem<\/td>\n<\/tr>\n<tr>\n<td>List help topics containing x<\/td>\n<td>Get-Help string (string is a prefix or uses wildcards)<\/td>\n<td>[1a] help Get<br \/>[1b] help Get-*<\/td>\n<\/tr>\n<tr>\n<td>Help for parameter y of cmdlet x<\/td>\n<td>Get-Help cmd -parameter y<\/td>\n<td>help Get-Date -param month<\/td>\n<\/tr>\n<tr>\n<td>Help for multiple parameters<\/td>\n<td>Get-Help cmd -parameter y* (i.e. use wildcards)<\/td>\n<td>help Get-Date -param m*<\/td>\n<\/tr>\n<tr>\n<td>List allowed values for parameter y of cmdlet x<\/td>\n<td>Get-Help cmd -parameter y<\/td>\n<td>help Out-File -parameter Encoding<\/td>\n<\/tr>\n<tr>\n<td>Intellisense for parameter names [in ISE]<\/td>\n<td>cmdlet  -paramNamePrefix<\/td>\n<td>Out-File -enc<\/td>\n<\/tr>\n<tr>\n<td>Intellisense for parameter values [in ISE]<\/td>\n<td>cmdlet  -paramName&lt;space&gt; paramValuePrefix<\/td>\n<td>Out-File -enc&lt;space&gt;<\/td>\n<\/tr>\n<tr>\n<td>Auto-completion for parameter names<\/td>\n<td>cmdlet  &#8211; paramNamePrefix &lt;tab&gt;<\/td>\n<td>[1a] Out-File -&lt;tab&gt;<br \/>[1b] Out-File -enc&lt;tab&gt;<\/td>\n<\/tr>\n<tr>\n<td>Auto-completion for parameter values<\/td>\n<td>cmdlet  -paramName&lt;space&gt; paramValuePrefix &lt;tab&gt;<\/td>\n<td>[1a] Out-File -enc&lt;space&gt;&lt;tab&gt;<br \/>[1b] Out-File -enc&lt;space&gt;u&lt;tab&gt;<\/td>\n<\/tr>\n<tr>\n<td>List all &#8216;conceptual&#8217; topics (see text above)<\/td>\n<td>Get-Help about_*<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>Filter help output by regex<\/td>\n<td>Get-Help topic | Out-String -stream | sls -pattern regex<\/td>\n<td>help ls | Out-String -Stream | Select-String recurse<\/td>\n<\/tr>\n<tr>\n<td>Filter help output by constant<\/td>\n<td>Get-Help topic | Out-String -stream | sls -simple text<\/td>\n<td>help ls | Out-String -Stream | sls -SimpleMatch &#8220;[-recurse]&#8221;<\/td>\n<\/tr>\n<tr>\n<td>Send help text to a file<\/td>\n<td>[1] Get-Help topic| Out-String | Set-Content file<br \/>[2] Get-Help topic &gt; file<\/td>\n<td>[1] help Get-ChildItem  | Out-String | sc help.txt<br \/>[2] help Get-ChildItem &gt; help.txt<\/td>\n<\/tr>\n<tr>\n<td>List all cmdlets and functions<\/td>\n<td>Get-Command<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List all cmdlets\/functions beginning with characters<\/td>\n<td>Get-Command string*<\/td>\n<td>gcm wr*<\/td>\n<\/tr>\n<tr>\n<td>List all cmdlets\/functions filtered by noun<\/td>\n<td>Get-Command -noun string*<\/td>\n<td>gcm -noun type*<\/td>\n<\/tr>\n<tr>\n<td>List all exported items from module x<\/td>\n<td>Get-Command -Module module<\/td>\n<td>Get-Command -Module BitLocker<\/td>\n<\/tr>\n<tr>\n<td>List properties and methods of cmdlet<\/td>\n<td>cmdlet | Get-Member<\/td>\n<td>Get-ChildItem | gm<\/td>\n<\/tr>\n<tr>\n<td>List meta-details of cmdlet  (see text above)<\/td>\n<td>Get-Command cmdlet | Select-Object *<\/td>\n<td>gcm Get-ChildItem | select *<\/td>\n<\/tr>\n<tr>\n<td>Display module containing cmdlet<\/td>\n<td>(Get-Command cmdlet).ModuleName<\/td>\n<td>(gcm Get-ChildItem).ModuleName<\/td>\n<\/tr>\n<tr>\n<td>Display assembly containing cmdlet (for compiled cmdlets)<\/td>\n<td>( Get-Command cmdlet ).dll<\/td>\n<td>(gcm Get-ChildItem).dll<\/td>\n<\/tr>\n<tr>\n<td>Display underlying command for alias x<\/td>\n<td>Get-Alias -name x<\/td>\n<td>Get-Alias -name gci<\/td>\n<\/tr>\n<tr>\n<td>Display aliases for command x<\/td>\n<td>Get-Alias -definition x<\/td>\n<td>Get-Alias -def Get-ChildItem<\/td>\n<\/tr>\n<tr>\n<td>Get general help for PS Community Extensions<\/td>\n<td>Import-Module pscx; Get-Help pscx &lt;&lt;pscx&gt;&gt;<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List all functions in PSCX<\/td>\n<td>Get-Command -Module Pscx* -CommandType Function &lt;&lt;pscx&gt;&gt;<\/td>\n<td>same<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Location, Location, Location<\/h2>\n<p>See where you are or where you have been and navigate to where you want to be; understand the difference between your PowerShell current location and your Windows working directory; get relative or absolute paths for files or directories.<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<\/tr>\n<tr>\n<td>Display current location (non-UNC paths)<\/td>\n<td>[1] Get-Location<br \/>[2] $pwd<br \/>[3] $pwd.Path<\/td>\n<td>[1] cd c:\\foo; pwd<br \/>[2] cd c:\\foo; $pwd<br \/>[3] cd c:\\foo; $pwd.Path<\/td>\n<\/tr>\n<tr>\n<td>Display current location (UNC paths)<\/td>\n<td>$pwd.ProviderPath<\/td>\n<td>cd \\\\localhost\\c$; $pwd.ProviderPath<\/td>\n<\/tr>\n<tr>\n<td>Change  current location (to  drive or folder  or data store)<\/td>\n<td>Set-Location target<\/td>\n<td>[1a] cd variable:<br \/>[1b] sl c:\\documents\\me<br \/>[1c] chdir foo\\bar<\/td>\n<\/tr>\n<tr>\n<td>Get absolute path of file in current location<\/td>\n<td>Resolve-Path file<\/td>\n<td>Resolve-Path myfile.txt<\/td>\n<\/tr>\n<tr>\n<td>Get name without path for file or directory<\/td>\n<td>[1] (Get-Item filespec).Name<br \/>[2] Split-Path filespec -Leaf<\/td>\n<td>[1] (Get-Item \\users\\me\\myfile.txt).Name<br \/>[2] Split-Path \\users\\me -Leaf<\/td>\n<\/tr>\n<tr>\n<td>Get parent path for file<\/td>\n<td>(Get-Item filespec).DirectoryName<\/td>\n<td>(Get-Item \\users\\me\\myfile.txt).DirectoryName<\/td>\n<\/tr>\n<tr>\n<td>Get parent path for directory<\/td>\n<td>(Get-Item filespec).Parent<\/td>\n<td>(Get-Item \\users\\me).Parent<\/td>\n<\/tr>\n<tr>\n<td>Get parent path for file or directory<\/td>\n<td>Split-Path filespec -Parent<\/td>\n<td>[1a] Split-Path \\users\\me\\myfile.txt -Parent<br \/>[1b] Split-Path \\users\\me -Parent<\/td>\n<\/tr>\n<tr>\n<td>Get parent name without path for file<\/td>\n<td>(Get-Item filespec).Directory.Name<\/td>\n<td>(Get-Item \\users\\me\\myfile.txt).Directory.Name<\/td>\n<\/tr>\n<tr>\n<td>Get parent name without path for file or directory<\/td>\n<td>[1] (Get-Item (Split-Path filespec -Parent)).Name<\/p>\n<p>[2] Split-Path (Split-Path filespec -Parent) -Leaf<br \/>[3] &#8220;filespec&#8221;.split(&#8220;\\&#8221;)[-2]<\/td>\n<td>[1] (Get-Item (Split-Path \\users\\me\\myfile.txt -Parent)).Name<br \/>[2] Split-Path (Split-Path \\users\\me -Parent) -Leaf<br \/>[3a] &#8220;\\users\\me\\myfile.txt&#8221;.split(&#8220;\\&#8221;)[-2]<br \/>[3b] &#8220;\\users\\me&#8221;.split(&#8220;\\&#8221;)[-2]<\/td>\n<\/tr>\n<tr>\n<td>Display working directory (see http:\/\/bit.ly\/1j4uomr)<\/td>\n<td>[Environment]::CurrentDirectory<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>Change current location and stack it<\/td>\n<td>Push-Location path<\/td>\n<td>pushd \\projects\\stuff<\/td>\n<\/tr>\n<tr>\n<td>Return to last stacked location<\/td>\n<td>Pop-Location<\/td>\n<td>popd<\/td>\n<\/tr>\n<tr>\n<td>View directory stack<\/td>\n<td>Get-Location -stack<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>View directory stack depth<\/td>\n<td>(Get-Location -stack).Count<\/td>\n<td>same<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Files and Paths and Things<\/h2>\n<p>You can list contents of disk folders with Get-ChildItem just as you could use dir from DOS. But Get-ChildItem also lets you examine environment variables, local variables, aliases, registry paths, even database objects with the same syntax! See about_providers (http:\/\/bit.ly\/1ghdcvb) and PS Provider Help (http:\/\/bit.ly\/1dHlC7r) for more details.<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<\/tr>\n<tr>\n<td>List contents of location<br \/>(location may be on any supported PSDrive-see list datastores below). <\/td>\n<td>[1] Get-ChildItem path<\/p>\n<p>[2] Get-ChildItem psdrive:path <\/p>\n<p>[3] Get-ChildItem psdrive:<\/td>\n<td>[1a] Get-ChildItem<br \/>[1b] Get-ChildItem .<br \/>[2a] gci c:\\users\\me\\documents<br \/>[2b] ls  SQLSERVER:\\SQL&#194;&#173;\\localhost&#194;&#173;\\SQLEXPRESS\\&#194;&#173;Databases <br \/>[3a] dir env:<br \/>[3b] dir variable:<br \/>[3c] ls alias:<\/td>\n<\/tr>\n<tr>\n<td>List names of files in current directory<\/td>\n<td>[1] Get-ChildItem  | select -ExpandProperty name<br \/>[2] dir  | % { $_.Name }<br \/>[3] (dir).Name<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List names of files recursively<\/td>\n<td>[1] dir -Recurse | select -ExpandProperty Name<br \/>[2] (dir -Recurse).Name<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List full paths of files recursively<\/td>\n<td>[1] dir -Recurse | select -ExpandProperty FullName<br \/>[2] (dir -Recurse).FullName<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List full paths of files recursively with directory marker<\/td>\n<td>dir -r | % { $_.FullName + $(if ($_.PsIsContainer) {&#8216;\\&#8217;}) }<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List relative paths of files recursively with directory marker<\/td>\n<td>dir -r | % { $_.FullName.substring($pwd.Path.length+1) + $(if ($_.PsIsContainer) {&#8216;\\&#8217;}) }<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List file and directory sizes<br \/>(see http:\/\/stackoverflow.com\/a\/14031005)<\/td>\n<td>dir | % { New-Object PSObject -Property @{ Name = $_.Name; Size = if($_.PSIsContainer) { (gci $_.FullName -Recurse | Measure Length -Sum).Sum  } else {$_.Length}; Type = if($_.PSIsContainer) {&#8216;Directory&#8217;} else {&#8216;File&#8217;} } }<\/td>\n<td>same<\/td>\n<\/tr>\n<tr>\n<td>List datastores (regular filesystem drives plus drives from other providers)<\/td>\n<td>[1] Get-PSDrive<br \/>[2] Get-PSDrive -PSProvider provider<\/td>\n<td>[1] Get-PSDrive<br \/>[2] gdr -PSProvider FileSystem<\/td>\n<\/tr>\n<tr>\n<td>List providers (suppliers of datastores)<\/td>\n<td>[1] Get-PSProvider<br \/>[2] Get-PSProvider -PSProvider provider<\/td>\n<td>[1] Get-PSProvider<br \/>[2] Get-PSProvider -PSProvider registry<\/td>\n<\/tr>\n<tr>\n<td>List processes<\/td>\n<td>Get-Process<\/td>\n<td>same<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Basic Syntactic Elements<\/h2>\n<p>Like with learning most things, you need to learn to crawl before you can learn to run. This section shows you how to do some of the most basic but important things, things that will soon become second nature: knowing what is true and what is false; adding comments; continuing a command across multiple lines or, contrariwise, combining multiple commands on one line; and so forth. Arguably there should be one other important group of items included here: PowerShell operators. But I already published a wallchart on a set of common operators for strings and string arrays. See Harnessing PowerShell&#8217;s String Comparison and List-Filtering Features (http:\/\/bit.ly\/1c20itX) for details on -eq, -like, -match, and -contains operators and their variations.<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Element<\/td>\n<td>Example<\/td>\n<td>Output<\/td>\n<\/tr>\n<tr>\n<td>End-of-line comment<\/td>\n<td># (octothorp)<\/td>\n<td>52 # number of weeks in a year<\/td>\n<td>52<\/td>\n<\/tr>\n<tr>\n<td>Block comment or documentation comment<\/td>\n<td>&lt;# &#8230; #&gt;<\/td>\n<td>&lt;# multi-line<br \/>comment here #&gt;<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Continue command on multiple lines (required unless break after pipe or curly bracket)<\/td>\n<td>` (backquote as last character on line)<\/td>\n<td>&#8220;hello &#8221; + `<br \/>&#8220;world&#8221;<\/td>\n<td>hello world<\/td>\n<\/tr>\n<tr>\n<td>Combine commands on a single line<\/td>\n<td>; (semicolon)<\/td>\n<td>$a = 25; $b = -9; &#8220;$a, $b&#8221;<\/td>\n<td>25, -9<\/td>\n<\/tr>\n<tr>\n<td>Escape next character<\/td>\n<td>` (backquote)<\/td>\n<td>$a = 25; &#8220;value of `$a is $a&#8221;<\/td>\n<td>value of $a is 25<\/td>\n<\/tr>\n<tr>\n<td>Non-printable characters (newline, tab, etc.)<\/td>\n<td>`n, `t<\/td>\n<td>&#8220;line one`n line two&#8221;<\/td>\n<td>line one<br \/> line two<\/td>\n<\/tr>\n<tr>\n<td>Boolean constant TRUE<br \/>(see <a href=\"http:\/\/stackoverflow.com\/a\/16819045\">here<\/a> <br \/>and http:\/\/bit.ly\/1iGhXOW)<\/td>\n<td>[1] $TRUE<br \/>[2] Any string of length &gt; 0<br \/>[3] Any number not equal to 0<br \/>[4] Array of length &gt; 1<br \/>[5] Array of length 1 whose element is true<br \/>[6] A reference to any object<\/td>\n<td>[1] if ($TRUE) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[2] if (&#8220;abc&#8221;) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[3] if (-99.5) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[4] if ((1, 2)) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[5] if ((1)) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[6] $a = 25; if ([ref]$a) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<\/td>\n<td>true<br \/>true<br \/>true<br \/>true<br \/>true<br \/>true<\/td>\n<\/tr>\n<tr>\n<td>Boolean constant FALSE<br \/>(see <a href=\"http:\/\/stackoverflow.com\/a\/16819045\">here<\/a>)<\/td>\n<td>[1] $FALSE<br \/>[2] Empty string<br \/>[3] Any number = 0 (e.g. 0, 0.0, 0x0, 0mb, 0D, &#8230;)<br \/>[4] Array of length 0<br \/>[5] Array of length 1 whose element is false<br \/>[6] $NULL<\/td>\n<td>[1] if ($FALSE) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[2] if (&#8220;&#8221;) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[3] if (0x0) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<\/p>\n<p>[4] if (@()) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[5] if ((&#8220;&#8221;)) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<br \/>[6] if ($NULL) { &#8220;true&#8221; } else { &#8220;not true&#8221; }<\/td>\n<td>not true<br \/>not true<br \/>not true<br \/>not true<br \/>not true<br \/>not true<\/td>\n<\/tr>\n<tr>\n<td>null<\/td>\n<td>$null<\/td>\n<td>$null<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Iterate each element in a list<\/td>\n<td>ForEach-Object<\/td>\n<td>1..3 | % { $_ * 2 }<\/td>\n<td>2<br \/>4<br \/>6<\/td>\n<\/tr>\n<tr>\n<td>Ternary operator, scalar<br \/>(e.g. result = a &gt; b ? x : y; )<\/td>\n<td>[1] $result = switch (boolExpr) { $true { $x } $false { $y } }<br \/>[2] $result = if (boolExpr) { $x } else { $y }<br \/>[3] $result = ?: {boolExpr} {$x} {$y} &lt;&lt;pscx&gt;&gt;<\/td>\n<td>[1] $result = switch (25 -gt 10) { $true { &#8220;yes&#8221; } $false { &#8220;no&#8221; } }<br \/>[2] $result = if (25 -gt 10) { &#8220;yes&#8221; } else { &#8220;no&#8221; }<\/td>\n<td>yes<br \/>yes<\/td>\n<\/tr>\n<tr>\n<td>Coalesce (evaluate 2nd block if 1st block is null)<br \/>Define Coalesce-Args as:<br \/>function Coalesce-Args&#160; { (@($args | ?{$_}) + $null)[0] }; Set-Alias ?? Coalesce-Args<\/td>\n<td>[1] Invoke-NullCoalescing block1 block2 &lt;&lt;pscx&gt;&gt;<\/p>\n<p>[2] Coalesce-Args block1 block2<br \/>&lt;&lt;code from http:\/\/bit.ly\/KhMkwO&gt;&gt;<\/td>\n<td>[1a] Invoke-NullCoalescing {$env:dummy} {&#8220;\\usr\\tmp&#8221;}<br \/>[1b] ?? {$env:dummy} {&#8220;\\usr\\tmp&#8221;}<br \/>[2a] Coalesce-Args $env:dummy &#8220;\\usr\\tmp&#8221;<br \/>[2b] ?? $env:dummy &#8220;\\usr\\tmp&#8221;<\/td>\n<td>\\usr\\tmp<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Display Options<\/h2>\n<p>According to Using Format Commands to Change Output View (http:\/\/bit.ly\/N8b7oe) each format cmdlet (i.e. Format-Table and Format-List) has default properties that will be used if you do not specify specific properties to display. But the documentation does not reveal what those defaults are or how they vary depending on the type of input object. Also, the default properties differ between Format-Table and Format-List. Finally, keep in mind that if Select-Object is the last cmdlet in your command sequence, it implicitly uses Format-Table or Format-List selecting one or the other based on the number and width of output fields. (And while the included images were not designed for you to make out the actual text, you can discern the representation of the data from those thumbnails.)<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<\/tr>\n<tr>\n<td>Format list of objects with each field on a separate line<\/td>\n<td>any | Format-List<\/td>\n<td>ls C:\\Windows\\temp | select name,length | Format-List<\/td>\n<\/tr>\n<tr>\n<td>Format list of objects with all fields on one line<\/td>\n<td>any | Format-Table<\/td>\n<td>ls C:\\Windows\\temp | select name,length | Format-Table<\/td>\n<\/tr>\n<tr>\n<td>Format list of objects in an interactive grid<\/td>\n<td>any | Out-GridView<\/td>\n<td>ls C:\\Windows\\temp | select name,length | Out-GridView<\/td>\n<\/tr>\n<tr>\n<td>Format list as console graph<\/td>\n<td>any | Out-ConsoleGraph -property quantityPropertyName &lt;&lt;code from http:\/\/bit.ly\/1jJN4tG&gt;&gt;<\/td>\n<td>ls C:\\Windows\\temp | select name,length | Out-ConsoleGraph -property length<\/td>\n<\/tr>\n<tr>\n<td>Format list as gridview graph<\/td>\n<td>any | Out-ConsoleGraph -GridView -property quantityPropertyName<br \/>&lt;&lt;code from http:\/\/bit.ly\/1jJN4tG&gt;&gt;<\/td>\n<td>ls C:\\Windows\\temp | select name,length | Out-ConsoleGraph -property length -grid<\/td>\n<\/tr>\n<tr>\n<td>Send table-formatted output to file<\/td>\n<td>[1] any | Format-Table -AutoSize |<br \/>Out-File file -Encoding ascii<br \/>[2] any | Format-Table -AutoSize |<br \/>Out-String | Set-Content file<\/td>\n<td>[1] ps | ft -auto |Out-File process.txt -enc ascii<\/p>\n<p>[2] ps | ft -auto |Out-String | sc process.txt<\/td>\n<\/tr>\n<tr>\n<td>Send trimmed table-formatted output to file (removes trailing spaces on fields as well as blank lines)<\/td>\n<td>any | Format-Table -AutoSize | Out-String -Stream | ForEach { $_.TrimEnd() } |where { $PSItem } |<br \/>Set-Content file<\/td>\n<td>ps | ft -auto| Out-String -Stream | %{ $_.TrimEnd() } | ? { $_ } | sc file<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Prompts and Pauses<\/h2>\n<p>Some basic interactivity entries, showing how to get input from a user, how to pause and resume, and how to clear the window contents.<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<\/tr>\n<tr>\n<td>Prompt user for input<\/td>\n<td>Read-Host prompt<\/td>\n<td>$userValue = Read-Host &#8220;Enter name&#8221;<\/td>\n<\/tr>\n<tr>\n<td>Pause for a specific time period<\/td>\n<td>Start-Sleep seconds<\/td>\n<td>&#8220;before&#8221;; Start-Sleep 5; &#8220;after&#8221;<\/td>\n<\/tr>\n<tr>\n<td>Pause a script and resume with Enter key<\/td>\n<td>Read-Host -Prompt promptString<\/td>\n<td>Read-Host -Prompt &#8220;Press enter to continue&#8230;&#8221;<\/td>\n<\/tr>\n<tr>\n<td>Pause a script and resume with any key<br \/>(does not work in PowerShell ISE)<\/td>\n<td>Write-Host &#8220;Press any key to continue &#8230;&#8221;;<br \/>$x = $host.UI.RawUI.ReadKey(&#8220;NoEcho,IncludeKeyDown&#8221;)<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Clear screen<\/td>\n<td>Clear-Host<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Display progress bar<\/td>\n<td>Write-Progress -Activity title -status event -percentComplete percentage<\/td>\n<td>for ($i = 0; $i -lt $stuff.Count; $i++)<br \/># primary code here<br \/>Write-Progress -Activity $title -status $label[$i] -percent (($i + 1) \/ $stuff.Count*100)<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Casts, Type Accelerators, and .NET Classes <\/h2>\n<p>You are no doubt familiar with type casting in .NET languages. PowerShell provides the same casting capability but enhances it with a new concept, type accelerators. Type accelerators are simply aliases for .NET framework classes. Note that in PowerShell you can always omit the &#8220;System.&#8221; prefix of a class if it has one to save typing, so you could use, say, DateTime rather than System.DateTime. But with type accelerators you can get a lot more concise than that. For example, you can just use [wmi] instead of System.Management.ManagementObject. As far as casting, in PowerShell you can cast to any .NET type that has either a cast operator or a constructor that accepts the source type (see the Net.IpAddress entry below). Finally, you can use .NET type names to access static members of .NET classes (see the DateTime.Now entry below).<\/p>\n<table>\n<tbody>\n<tr>\n<td>Action<\/td>\n<td>Command<\/td>\n<td>Example<\/td>\n<td>Output<\/td>\n<\/tr>\n<tr>\n<td>List all type accelerators (see <a href=\"http:\/\/stackoverflow.com\/a\/16947910\/115690\">here<\/a>)<\/td>\n<td>[1] [accelerators]::get &lt;&lt;pscx&gt;&gt;<br \/>[2] [psobject].assembly.gettype( &#8220;System.Management.Automation.TypeAccelerators&#8221;)::Get<\/td>\n<td>same<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Cast string to IPAddress object<\/td>\n<td>[System.Net.IpAddress]&#8221;ip-address&#8221;<\/td>\n<td>[Net.IpAddress]&#8217;192.0.0.1&#8242;<\/td>\n<td>Address            : 16777408<br \/>AddressFamily      : InterNetwork<br \/>. . .<br \/>IsIPv4MappedToIPv6 : False<br \/>IPAddressToString  : 192.0.0.1<\/td>\n<\/tr>\n<tr>\n<td>Create new DateTime object with constructor<\/td>\n<td>New-Object -TypeName DateTime<br \/>-ArgumentList constructor-argument-list<\/td>\n<td>New-Object -TypeName DateTime<br \/>-ArgumentList 2014,10,10<\/td>\n<td>Friday, October 10, 2014 12:00:00 AM<\/td>\n<\/tr>\n<tr>\n<td>Cast string to a DateTime object<\/td>\n<td>[DateTime]&#8221;date-time value&#8221;<\/td>\n<td>[DateTime]&#8221;10\/10\/2014&#8243; |<br \/>select Year,  DayOfWeek, Ticks<\/td>\n<td>Year DayOfWeek              Ticks<br \/>&#8212;-&#160;&#160;&#160; &#8212;&#8212;&#8212;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;              &#8212;&#8211;<br \/>2014    Friday 635484960000000000<\/td>\n<\/tr>\n<tr>\n<td>Cast string to XML without accelerator<\/td>\n<td>[System.Xml.XmlDocument] &#8220;XML text&#8221;<\/td>\n<td>[System.Xml.XmlDocument] &#8220;&lt;root&gt;text&lt;\/root&gt;&#8221;<\/td>\n<td>root                                                                                                                                    <br \/>&#8212;-                                                                                                                                    <br \/>text<\/td>\n<\/tr>\n<tr>\n<td>Cast string to XML with accelerator<\/td>\n<td>[xml] &#8220;XML text&#8221;<\/td>\n<td>[xml] &#8220;&lt;root&gt;text&lt;\/root&gt;&#8221;<\/td>\n<td>root                                                                                                                                    <br \/>&#8212;-                                                                                                                                    <br \/>text<\/td>\n<\/tr>\n<tr>\n<td>Access static member of .NET class<\/td>\n<td>[class]::member<\/td>\n<td>$currentTime = [datetime]::Now<\/td>\n<td><\/td>\n<\/tr>\n<tr>\n<td>Cast integer to Boolean <\/td>\n<td># [bool]2 yields True; [bool]0 yields False<\/td>\n<td><\/td>\n<td><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Conclusion<\/h2>\n<p>That&#8217;s it for part 1; keep an eye out for more in the near future! While I have been over the recipes presented numerous times to weed out errors and inaccuracies, I think I may have missed one. If you locate it, please share your findings in the comments below!<\/p>\n<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>PowerShell is designed to be used by busy IT professionals who want to get things done, and don&#8217;t necessarily enjoy programming. PowerShell tackles this paradox by providing its own help and command-line intellisense. We aim to make it a bit easier still by providing a series of collections of general-purpose one-liners to cover most of what you&#8217;ll need to get useful scripting done.&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":[4178,4635,4871],"coauthors":[6802],"class_list":["post-1787","post","type-post","status-publish","format-standard","hentry","category-powershell","tag-bi","tag-powershell","tag-sysadmin"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1787","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=1787"}],"version-history":[{"count":4,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1787\/revisions"}],"predecessor-version":[{"id":66971,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1787\/revisions\/66971"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=1787"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=1787"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=1787"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=1787"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}