Powershell for devs, part 2

Continuing from Part1.

New to Powershell? Let me jot down a few good-to-know things. Some you already know. Some might save you hours of googling.

Below is a simple module. I will explain it row(s) by row(s).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Set-StrictMode -Version 2.0

< #
.SYNOPSIS
Short description.

.DESCRIPTION
Long description.

.PARAMETER name
This does not show with Get-Help.

.PARAMETER birthDate
This does not show with Get-Help.

.EXAMPLE
An example...

.NOTES
General notes.
#>
function Get-PersonData
{
    param(
        [parameter(
            Mandatory=$true,
            HelpMessage='The name of the culprit.'
        )]
        [string] $name,
        [datetime] $birthDate = (Get-Date)
    )
    $startTime = Get-Date -Format 't'
    Write-Verbose "Start:$startTime"
   
    "Name=$name, Date=$($birthDate.ToString('yyyyMMdd'))."

    # Call method | Filter | Sort | Return.
    $foundPerson = GetPeople `
        | where {$_.name -eq $name } `
        | Sort-Object born `
        | Select-Object -First 1

    Write-Host "foundPerson:[$foundPerson]"
   
    Write-Verbose "Stop:$(Get-Date -Format 't')"

    return $foundPerson
}

function GetPeople(){
    # Create array of key-value pairs.
    $people =
        @{name='ola';born=[DateTime]'1970-10-13';children=1},
        @{name='anders';born=[DateTime]'2011-01-01'}

    return $people
}

Export-ModuleMember Get-PersonData
# Export-ModuleMember GetPeople
1
Set-StrictMode

Use Set-StrictMode. See part1 of this blog series.

1
# .SYNOPSIS... #

This type of comment right before a method is recognised by Powershell and ends up in Get-Help.  Adhering to explaining the intention for your methods is considered good practice.

Inside the method is

1
2
3
4
5
6
7
8
param(
    [parameter(
        Mandatory=$true,
        HelpMessage='The name of the culprit.'
    )]
    [string]$name,
    [datetime]$birthDate=(Get-Date)
)

This is what the parameters look like. One can set if a parameter is mandatory, some help text to be picked up by your favourite text editor, the [type] and default value.

1
$startTime=Get-Date-Format 't'

A variable is set to a string. Other scripting languages send strings around. Powershell sends proper objects. The Get-Date-Format converts the DateTime value to a string.

1
Write-Verbose "Start$startTime"

Built into Powershell is the possibility to call (almost) anything with a -Verbose flag. Only then is the Write-Verbose called. Like a simple logging level.

1
"Name=$name, Date=$($birthDate.ToString('yyyyMMdd'))."

Nothing strange here at first sight. Until you exeute in a console. Then you realise this string is outputed; because it is not inputed into something else, like a variable.

Also “$($variable.Method)” is the way to call methods inside a string.

1
2
3
4
$foundPerson= GetPeople `
    | where {$_.name-eq$name } `
    | Sort-Object born `
    | Select-Object-First 1

Powershell is said to be able to use Linq. This is technically true but the syntax is so weird that I have never used it. This code though has (almost) the same behaviour and is easy to read.

GetPeople is a method call. Backtick concatenate lines and circumvents that Powershell has automatic statement ending with a line end. | pipes object and not strings. where is an alias for Where-Object. The rest is… Linqish.

1
Write-Host "foundPerson:[$foundPerson]"

Write-Host an object like $foundPerson output the contents of the object. Not just the type as in C#.
Write-Verbose “Stop:$(Get-Date-Format ‘t’)”
This string is outputed only if the method call is made with -Verbose. Plus an exmple on how to write a method call in a string.

1
return $foundPerson

Finally nothing surprising. Except that return can be left out to make the code harder to read.

1
2
3
$people=
@{name='ola';born=[DateTime]'1970-10-13';children=1},
@{name='anders';born=[DateTime]'2011-01-01'}

@ tells Powershell to create a list of key-value pairs. Also often called a hash list.

Note the comma character. That makes $people an array of key-value pairs.

1
Export-ModuleMember Get-PersonData

Only exported mehods are visible outside the module. It is like making them public.

Tags:

Leave a Reply