Testing in PowerShell

I made a thing! A thing in PowerShell!

I’m not really sure how to make a module in PowerShell, but I made functions to do these epoch conversions and put them in a .psm1 file. Don’t know if there’s more to it or not.

Naturally, I wanted to write tests as I worked. I discovered that there is no testing framework in PowerShell, but there’s a terrific third-party framework called Pester. Since PowerShell on Linux is so new, I had no idea if it was going to work. I was pleased when it installed without issue, but at first it didn’t appear to work. Turns out it was assuming I had a $env:TEMP defined, but I had not. I took a guess and just set it to /tmp

$env:TEMP = '/tmp'

and then all was well! When you are in the directory where your module and tests are, you can import your module with

Import-Module ./Epochs

and then run your tests with

Invoke-Pester

That is, if we’ve named everything the way Pester expects, we just take all the defaults!

I learned the hard way that PowerShell won’t re-import a module it has already imported, by default. Making changes to Epochs.psm1 and then doing

Import-Module ./Epochs
Invoke-Pester

made me think my tests were still passing with my code changes, but it hadn’t actually reloaded my module. You have to -force it

Import-Module ./Epochs -force
Invoke-Pester

I’m still stumbling around when it comes to PowerShell, but Pester makes me feel more at home!

Testing in PowerShell

Hello, PowerShell!

Last week, while I was at Abstractions, I heard that PowerShell for Linux was released. Today, I tried it out!

My desktop machine at home is currently running Xubuntu 16.04.1, which is one of the platforms already packaged up. I downloaded the .deb, checked its sum

$ sha256sum Downloads/powershell_6.0.0-alpha.9-1ubuntu1.16.04.1_amd64.deb 
5d56a0419c23ce879dd4ddaca009f03e888355fccc9eecf882b64d63da5f38e3 Downloads/powershell_6.0.0-alpha.9-1ubuntu1.16.04.1_amd64.deb

and followed their instructions. I already had the two dependencies, so

$ sudo apt install libunwind8 libicu55

had no effect. Installing their deb

$ sudo dpkg -i ~/Downloads/powershell_6.0.0-alpha.9-1ubuntu1.16.04.1_amd64.deb

gave me a powershell executable.

$ which powershell
/usr/bin/powershell

Writing a quick hello world in PowerShell with that as the shebang line

#!/usr/bin/powershell

$name = $args[0]
if (!$name) {
    $name = "World"
}

write-host "Hello, $name!"

worked great!

$ ./hello.ps1
Hello, World!

$ ./hello.ps1  foo
Hello, foo!

Okay, how about those regexes with multiple named captures I talked about a while back? If we write this in multicapture.ps1

#!/usr/bin/powershell

$string = 'foo bar baz'
$pat = [regex] "(?:(?<word>\w+)\W*)+"
$m = $pat.match($string)
$m.groups["word"].captures | %{$_.value}

then lo and behold we get

$ ./multicapture.ps1 
foo
bar
baz

Now that I don’t have to boot Windows to do it, I might play with PowerShell a lot more! Thanks, Microsoft!

Hello, PowerShell!