Powershell is very useful for quick queries or repeatable scripts.
Scripts can be shared, tested, adapted and reused.
Here are a few key points about powershell:
- It does have an odd syntax – but does have good reasons for this.
- It is very consistent (except about brackets)
- It is secure by default
- Everything is an object
- Everything is discoverable
- Help is always available for those that ask
- Pipelines are powerful but are not the solution to everything
- Cmdlets are intended to be combined.
Simple Functions
I’ll start with a function example.
function Test($a, $b)
{
“$a – $b”
}
This is a function written in the simple form (there are two advanced variations which I won’t go into here).
To call this you should use the following:
Test a b
This is the positional form of parameters.
Alternatively you could use:
Test -a a -b b
This is the named parameter form.
You can of course mix these up.
Test -b b a
You can even use a dictionary object to pass the parameters in:
$var = @{a=1;b=2}
test @var
However you will get odd behavior if you try and use brackets or commas:
Test(1,2)
1 2 –
Test 1,2
1 2 –
This is because brackets and commas create lists.
There is an exception to this when you are calling methods on .net objects.
[DateTime]::UtcNow.AddDays(-1)
Here brackets and commas are required.
Powershell even gives help details about custom functions.
get-help test
NAME
TestSYNTAX
Test [[-a] <Object>] [[-b] <Object>]ALIASES
NoneREMARKS
None
Cmdlets
All of the built in functions (called cmdlets) behave in exactly the same way as custom functions.
They have a very strong naming convention: Verb-Noun
The verb is one of a given list (get-verb gives you the list, currently there are 98)
The noun is by convention singular.
They are intended to be composed in a pipeline.
The rule is anything not bound to a variable or cast to null is passed down the pipeline.
The following is how I determined how many verbs there are:
get-verb | Measure-Object | select count
Comparison operations.
Powershell uses the normal > and < symbols for file redirection (because it is backwards compatible with dos).
This means that you need to use the switch versions of these.
This is where the built in help comes in handy:
get-help about_ | Out-GridView
get-help about_comp -ShowWindow
Aliases
Some commands have short aliases:
get-alias
These typically map back to the dos or unix command that they resemble.
Pipeline
The command prompt in powershell forms a read-evaluate-print-loop.
1..10
1..10 | % {write-host “Hello $_”}
1..10 | sort -Descending | % {write-host “Hello $_”}
Each command in the chain will act as soon as it gets some data.
However greedy operators (such as sort) need the source to finish before passing parameters on.
Useful Cmdlets
where
get-member
out-gridview
import-csv