Top 10 PowerShell Parameters (Switches)

PowerShell's Top Ten Parameters, or -Switches

Most of PowerShell's commands can be fine-tuned with -parameters, otherwise known as switches.  My aim of this page is to encourage you keep a notebook of such useful PowerShell parameters.

Topics for PowerShell Parameters

 ♣

Guy's Top Ten PowerShell -Parameters

  1. -ErrorAction SilentlyContinue
  2. -MemberType (Get-Member)
  3. -Recurse with Get-ChildItem (Sub-directories)
  4. -Force with Get-ChildItem (Lists hidden files)
  5. -Auto (Adjust the width with Format-Table)
  6. -GroupBy (Collate similar items)
  7. -Filter (Get-WmiObject "Win32_Process")
  8. -List with Get-WmiObject (Get-Eventlog -List)
  9. -Com (New-Object)
  10. -WhatIf (Test before you commit)

Benefits of PowerShell Parameters

To begin with, let me explain the basics with an example; here is a command which searches just the top level container:  Get-Childitem C:\Windows\*

# PowerShell Parameter Example -Recurse
Get-Childitem C:\Windows\* -Recurse

Now when you add the -Recurse parameter, the command takes longer to execute, but it's well worth the time to drill down the directory tree, and find the file that you are seeking in a sub-directory.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

How to Research More PowerShell Parameters or -Switches

If you play strategic games like chess, you may be familiar with the idea of once you have found a good move, then look for an even better tactic.  So it is with PowerShell, if you find a good command such as Get-Eventlog system, look for parameter to refine the output, for example: Get-Eventlog system -newest 20.

Situation: You know the name of the cmdlet and want to investigate its parameters

The key question is how did I know about the -newest parameter, as PowerShell calls this appendage?  The answer is I called for help.  To be precise:

Clear-Host
Get-Help Get-Eventlog
# Or better still:
Get-Help -Eventlog -full

I recommend that you spend time studying the PARAMETERS section of any cmdlet that you are working with, you are sure to unearth one unexpected gem.

Situation: You know the parameters name, but want to find the cmdlet(s) name

For example, to see a list of cmdlets that support remoting try:

# Find a PowerShell Parameter
Get-Command | where { $_.parameters.keys -Contains "ComputerName"}

Modification to display just cmdlets with a particular PowerShell parameter.

Clear-Host
Get-Command| where { $_.parameters.keys -Contains "ComputerName"} `
| where {$_.CommandType -Contains "cmdlet"}

Note 1: Observe the backtick `.  Also there should be no space after that `.

Simplification employing PowerShell's -And :

# Research PowerShell Cmdlet
Clear-Host
Get-Command | where { $_.parameters.keys -Contains "ComputerName" `
-And $_.CommandType -Contains "cmdlet"}

See more on Get-Command itself

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer's Toolset v10

This Engineer's Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it's like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer's Toolset now!

Download your fully functional trial copy of the Engineer's Toolset v10

Fantastic Script to Research PowerShell Parameters

My real-life task was to research which PowerShell parameters contained -As, for example -AsHashTable.  I posted my question in the www.superuser.com forum, and this was a marvellous reply from Joey:

# Research PowerShell Parameters by Joey
Clear-Host
Get-Command | where { $_.CommandType -eq 'Cmdlet' } | Foreach { $_ | `
Add-Member -PassThru NoteProperty AsParameters ($_.Parameters.GetEnumerator() | `
Where {$_.Key -cmatch '^As([A-Z]|$)'} | Foreach { $_.Key }) } `
| Where { $_.AsParameters } | select Name, AsParameters

Note 2: The pattern I was looking for was 'As'.  Naturally, to research your parameters just substitute the text string you are interested in.

The Concept of an Optional, or an Assumed Parameter

If you digest every nuance of what Get-Help says, then you discover that each Parameter has properties, e.g.:
Required?  True or False
Position: 1 or 2 etc.

Both logic and practical experience show that if a parameter is not required, and it's in position 1, then you could safely omit it.  In other words the parameter is assumed.  Let us use Get-Childitem and -path as an example:

Get-Childitem -path C:\Windows

Get-Help Get-Childitem

# Results:
#    PARAMETERS
#       -path
#        Required? False
#        Position? 1

Thus Get-Childitem -path C:\Windows could be reduced to plain
Get-Childitem C:\Windows.   (or even: gci C:\Windows)

Another example of an assumed parameter comes from Get-Eventlog.  This command will not work unless you help PowerShell by supplying the name of the log.  The parameter is -LogFile.  For example Get-Eventlog -LogFile system.  However, PowerShell understands that the first word after eventlog is the name the log, and thus we can omit the -Logfile parameter.  PowerShell assumes that the only possible parameter in this position is -LogFile and the following command completes successfully: Get-Eventlog system.  See how to change Get-Eventlog's parameter defaults »

SolarWinds Response Time Viewer for WiresharkGuy Recommends: Response Time Viewer for Wireshark

Here is a free tool to troubleshoot network connection and latency problems.  Key concept: this is a free tool from SolarWinds that analyzes network packets captured by Wireshark (also a free tool).

When you inspect the data in the Response Time Dashboard, if you hover over an application such as Teredo or TCP, then you get an orange box showing a breakdown of network and application response times, note the 'Peak value' in addition to the 'Average'.

Download your free trial of SolarWinds Response Time Viewer for Wireshark

Abbreviating PowerShell Parameters

One source of confusion is that the same PowerShell parameter seems to have two or more forms, for example:  -ComputerName -computer or even -comp.  The explanation is that PowerShell's intelligence means that you only have to use sufficient letters to provide a unique combination that cannot be mistaken for any other parameter.

-foreground and -background example

# Abbreviating PowerShell Parameters
$Date = Get-Date
Write-Host $Date -ForeGroundColor green -b magenta
Write-Host $Date -fore yellow -back green
Write-Host $Date -f red -BackGroundColor black

The actual parameters are -ForegroundColor and -BackGroundColor, but as you can see, we can shorten them right down to -f  and -b. 

To improve the formatting of your parameters I recommend PowerShell splatting.

Guy's Second Series of Useful PowerShell Parameters (-Switches)

  1. -Path (Example of an optional or assumed parameter)
    -FilePath (Variation on -path, used with Out-file)
  2. -Query (WMI Select statement)
  3. -Replace (Select-String)
  4. -Pattern  (Select-String)
  5. -Descending (Sort-Object)
  6. -Value (Add-Content)
  7. -Newest (Get-Eventlog)
  8. -Last (Win32_Process pageFaults -last 5)
  9. -ComputerName (Useful scripts requiring loops) (-computer works equally well in most scripts)
  10. -UseTransaction  (new in PowerShell 2.0)

Guy Recommends: SolarWinds Free Wake-On-LAN UtilitySolarwinds Wake-On-LAN

Encouraging computers to sleep when they're not in use is a great idea - until you are away from your desk and need a file on that remote sleeping machine!

WOL also has business uses for example, rousing machines so that they can have update patches applied.  My real reason for recommending you download this free tool is because it's so much fun sending those 'Magic Packets'. Give WOL a try - it's free.

Download your free copy of SolarWinds Wake-On-LAN

New Parameter in PowerShell v 2.0 -online parameter

The technique is to add the parameter directly after the main command.  Remember to introduced your parameter with a -minus sign, and not a backslash.  If you apply the terminology strictly, then the difference between a parameter and a switch is that a switch does not take a value, whereas a parameter can.

Pattern Matching Switches

PowerShell also has a family of comparison or pattern matching switches.  You may see these conditional operators such as -Match and -Like in 'Where' clauses, for example:

Get-WmiObject -List | where {$_.name -Match "Win32"}

®

This family of switches has several names, conditional operators and pattern matching switches, let me introduce the family:

  1. -Match
  2. -Like
  3. -Contains

Sometimes logic dictates that their negative cousins produce tighter code, for example: -Notmatch

Although we are straying further from my original idea of switches to modify a command, I should mention the logical operators as they too are introduced by a -dash.

  1. -eq (Beware in PowerShell you cannot substitute an equals sign for -eq)
  2. -ne (Not equal, incidentally -neq will not work)
  3. -and
  4. -or

There are also bitwise variants -bor -band.  This is not an exhaustive list, there are exotic operators such as an exclusive or called -xor.

See how to change PowerShell's parameter defaults »

Summary of PowerShell's Parameters

We can modify the behaviour of PowerShell cmdlets by appending parameters.  In this way you can take a cmdlet's basic action and turn it to the outcome that you really want.  This is why spending time learning about parameters makes us better PowerShell scripters.

Understanding PowerShell's parameters will improve your scripts.  Firstly, you get extra capabilities, for example -Recurse, secondly you greater precision, for example -MemberType.  In conclusion, never miss a chance to research a Parameter or a Switch, if you find a really good example, email me and I will add it to Guy's top 10 Switches.

If you like this page then please share it with your friends

 


See more example of PowerShell's parameters

PowerShell Tutorials  • PowerShell Parameter Introduction  • Parameter Examples of Technique

Mandatory Parameters  • PowerShell $PSDefaultParameterValues  • Top 10 PowerShell Parameters

PowerShell Parameters Index  • Parameter Hashtable Splatting  • PowerShell 3.0 Default Parameters

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2016 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: