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
- How to research PowerShell Parameters or -Switches
- The Concept of an Optional, or an Assumed Parameter
- Abbreviating PowerShell Parameters
- Pattern Matching Switches
- Change Default Parameters
♣
Guy’s Top Ten PowerShell -Parameters
- -ErrorAction SilentlyContinue
- -MemberType (Get-Member)
- -Recurse with Get-ChildItem (Sub-directories)
- -Force with Get-ChildItem (Lists hidden files)
- -Auto (Adjust the width with Format-Table)
- -GroupBy (Collate similar items)
- -Filter (Get-WmiObject "Win32_Process")
- -List with Get-WmiObject (Get-Eventlog -List)
- -Com (New-Object)
- -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) 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
Guy 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 »
Guy 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)
- -Path (Example of an optional or assumed parameter)
-FilePath (Variation on -path, used with Out-file) - -Query (WMI Select statement)
- -Replace (Select-String)
- -Pattern (Select-String)
- -Descending (Sort-Object)
- -Value (Add-Content)
- –Newest (Get-Eventlog)
- -Last (Win32_Process pageFaults -last 5)
- -ComputerName (Useful scripts requiring loops) (-computer works equally well in most scripts)
- -UseTransaction (new in PowerShell 2.0)
Guy Recommends: SolarWinds Free Wake-On-LAN Utility
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"}
®