# Two hundred lines of PowerShell I could not test

> Why the nightly check moved to Python, what PowerShell still does better than anything else, and where the seam between the two belongs.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-02-12
- Tags: Python, PowerShell, Windows, Jenkins
- URL: https://deyanpeev.com/posts/two-hundred-lines-of-powershell-i-could-not-test

The drift check I wrote about a fortnight ago works. It has found three real
things. It's also two hundred and fourteen lines of PowerShell that I change
by editing a file, pushing, waiting for a nightly run, and reading a console
log at nine the next morning.

That isn't a language problem yet. The first fix was moving the script out of
the Jenkinsfile and into `ci/collect.ps1`, which gets you syntax highlighting,
a linter, and the ability to run it by hand. The second question is the one
that deserves an afternoon. Should the *logic* be PowerShell at all?

I moved it to Python. The argument follows, and it includes the places where
PowerShell wins.

# Five things I wanted

Tests I would write without being made to. Dependencies I could pin. The same
code runnable on the Linux controller, on the Windows agent and on my laptop.
A data model instead of a bag of `PSCustomObject`s. And errors that behave
like errors.

Four of those five are hard in PowerShell, and the fifth is the one that made
the decision.

# The error model

PowerShell has terminating errors, non-terminating errors,
`$ErrorActionPreference`, per-cmdlet `-ErrorAction`, `$?`, `$LASTEXITCODE`,
`throw`, `Write-Error`, `trap`, and a `try`/`catch` that only catches the
terminating kind. Nine mechanisms, and the default behaviour of most of them
is *keep going*.

So every serious PowerShell script starts with a two-line ritual to turn the
defaults off, and every native call gets wrapped so that a non-zero exit code
becomes an exception. It's the correct thing to write, but it is a lot of
scaffolding just to arrive at the behaviour Python has on line one.

```python
notafter = datetime.fromisoformat(cert["notAfter"])
```

If that fails, it raises, nothing after it runs, the process exits non-zero,
and Jenkins goes red. I've never written the Python equivalent of
`$ErrorActionPreference = 'Stop'` because there's nothing to write.

# Dependencies you can actually pin

`Install-Module` against the PowerShell Gallery has no lockfile. You can pin
one module with `-RequiredVersion`, by hand, per machine. A module manifest's
`RequiredModules` pins a *minimum*, not an exact version, and says nothing
about what those modules depend on in turn.

On a build agent that's the difference between reproducible and "worked in
January":

```bash
# requirements.txt
requests==2.27.1 \
  --hash=sha256:68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61
python-dateutil==2.8.2 \
  --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9
```

The agent installs from that file only:

```bash
pip install --require-hashes -r requirements.txt
```

With `--require-hashes`, pip refuses to install anything the file doesn't
name, or at a version it doesn't name, or with a hash that does not match. The
agent either gets the same tree the tests ran against or it gets an error.

# The one that decided it

This is the test I wanted to be able to write:

```python
def test_flags_a_certificate_expiring_inside_the_window():
    report = evaluate_certificates(
        certificates=[
            Certificate(subject="CN=build-signing", not_after=date(2022, 3, 1))
        ],
        today=date(2022, 2, 12),
        warn_within=timedelta(days=30),
    )
    assert [f.severity for f in report] == [Severity.WARN]
```

It needs no Windows machine, no certificate store, no Jenkins agent and no
night. It runs on the Linux controller in four milliseconds, so it runs on
every push instead of once a day.

Pester 5 is a real framework and I'm not going to pretend otherwise. But the
unit under test in a PowerShell script is usually a script, not a function with
parameters and a return value, and mocking a cmdlet is mocking a global. You
end up testing how your `Mock` calls look. The Python version is easy to test
because the certificate list arrives as an argument, and that has little to do
with Python. Nothing stops you writing PowerShell that way. Hardly anyone does
(me included), because the langauge does not push you towards it.

# A type checker instead of a two a.m. surprise

`Set-StrictMode -Version Latest` catches a misspelled property. It catches it
at runtime, on the agent, during the nightly run.

```python
@dataclass(frozen=True)
class Certificate:
    subject: str
    thumbprint: str
    not_after: datetime

@dataclass(frozen=True)
class Finding:
    check: str
    severity: Severity
    detail: str

def evaluate(facts: Facts, baseline: Baseline, *, today: date) -> list[Finding]:
    ...
```

`list[Finding]` without an import is 3.10, which came out in October. I'm on it
because 3.10.2 landed on the fourteenth of January and I had no reason to
wait. mypy in a pre-commit hook caught two real bugs in the first hour:
a `notAfter` that was a string on one code path and a `datetime` on another,
and a threshold compared against a ratio in one place and a percentage in the
other. The second one meant the disk check had never fired.

# JSON that survives the round trip

The check hands data between two languages, so this matters more than usual,
and Windows PowerShell 5.1 is awkward here.

`ConvertTo-Json` defaults to `-Depth 2` and replaces everything deeper with a
type name string. A single-element collection unrolls to the element, so one
machine emits an object where the others emit a list. `ConvertFrom-Json` in
5.1 gives you `PSCustomObject` and no `-AsHashtable` (that arrived in
PowerShell 6). Dates come out formatted according to whatever the process
culture is.

```python
json.dumps(payload)
```

Lists stay lists and dicts stay dicts, there's no depth limit, and
`json.dumps` of a `datetime` raises instead of guessing.

# One language on both sides of the wall

The same module runs under `pwsh` on the Windows agent, under `python3` on the
Linux controller, and in the pre-commit hook on my laptop. Last year's home
automation work was Python and this client's data tooling is Python. Keeping
the operations glue in a third language was a cost I was paying for no reason
other than "the machine is Windows".

And exit codes are free. `sys.exit(2)` and the build goes red. No wrapper
function, no `$LASTEXITCODE` after every call.

# Where PowerShell wins

It's already there. 5.1 is on every Windows machine you will ever be handed.
No installer, no virtual environment, no argument with anyone about what a
service account's `%APPDATA%` contains. For a script that runs once, on a box
you don't own, that outweighs everything else.

It also owns the Windows surface area: `Get-CimInstance Win32_LogicalDisk`, the
registry as a drive you can `cd` into, ACLs, the event log, scheduled tasks,
IIS, Active Directory, the certificate store as `Cert:\`. Every one of those is
one line. The Python equivalents are `pywin32` or WMI bindings, an afternoon,
and a worse object model at the end of it.

The object pipeline is better for interactive work than anything I can write
in Python: `Get-Service | Where-Object Status -eq Running |
Select-Object Name, StartType`.

WinRM and `Invoke-Command -ComputerName` are built in, authenticated and
encrypted by default. Python's story here is a third-party library and a longer
conversation with security.

And it is discoverable, with `Get-Help`, `Get-Member` and consistent verb-noun
naming. It's a better shell than it has any right to be.

But all of that is on the collecting side. The part of my script that decides
whether 12% free disk is a problem doesn't use any of it.

# So the seam goes here

PowerShell is a driver. Keep it thin enough to to read in one screen. It touches
the Windows-only APIs, emits JSON and exits. No thresholds, no formatting, no
decisions.

```powershell
# ci/collect.ps1 - facts only. Nothing in here has an opinion.
[CmdletBinding()]
param(
  [Parameter(Mandatory)][string]   $OutFile,
  [Parameter(Mandatory)][string[]] $ServiceNames
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

$facts = [ordered]@{
  computerName = $env:COMPUTERNAME
  collectedAt  = (Get-Date).ToUniversalTime().ToString('o')
  powerShell   = $PSVersionTable.PSVersion.ToString()
  executionPolicy = "$(Get-ExecutionPolicy -Scope LocalMachine)"
  disks = @(
    Get-CimInstance Win32_LogicalDisk -Filter 'DriveType = 3' | ForEach-Object {
      @{ id = $_.DeviceID; freeBytes = [int64]$_.FreeSpace; sizeBytes = [int64]$_.Size }
    }
  )
  services = @(
    Get-Service -Name $ServiceNames | ForEach-Object {
      @{ name = $_.Name; status = "$($_.Status)"; startType = "$($_.StartType)" }
    }
  )
  certificates = @(
    Get-ChildItem Cert:\LocalMachine\My | ForEach-Object {
      @{
        subject    = $_.Subject
        thumbprint = $_.Thumbprint
        notAfter   = $_.NotAfter.ToUniversalTime().ToString('o')
      }
    }
  )
}

$facts | ConvertTo-Json -Depth 6 | Set-Content -Path $OutFile -Encoding utf8
```

Forty-one lines. Every `@()` and every `"$( )"` in there has a reason. The
first stops a one-element collection from serialising as an object, and the
second stops an enum from arriving as a number on one box and a string on
another.
The ISO-8601 round-trip format with `ToUniversalTime()` means Python's
`datetime.fromisoformat` reads it without a timezone argument.

Then the part with opinions in it:

```python
def evaluate(facts: Facts, baseline: Baseline, *, today: date) -> list[Finding]:
    return [
        *_disks(facts.disks, baseline.min_free_ratio),
        *_services(facts.services, baseline.services),
        *_certificates(facts.certificates, today, baseline.cert_warn_within),
        *_policy(facts.execution_policy, baseline.execution_policy),
    ]
```

Sixty-one pytest cases against that, all of them running on Linux.

# Getting Python onto the agent without regretting it

Four things, learned the hard way.

## Not the Microsoft Store build

Under a service account it resolves to an app execution alias that isn't
installed for that user, and the error tells you the file is not found while
`where python` cheerfully prints a path.

## All-users MSI, and keep it off `PATH`

`InstallAllUsers=1 PrependPath=0`, then refer to it by full path or through the
`py -3.10` launcher. A build agent should never be guessing which Python it got.

## A virtual environment per job, inside the workspace

```bash
"C:\Python310\python.exe" -m venv .venv
.venv\Scripts\python.exe -m pip install --disable-pip-version-check "pip==22.0.3"
.venv\Scripts\python.exe -m pip install --require-hashes -r ci\requirements.txt
.venv\Scripts\python.exe -m driftcheck \
  --facts facts.json --baseline %BASELINE% --out drift.json
```

## Pin the environment, not just the packages

A service account has a profile, but it's not one anybody has looked at, and
the defaults for pip's cache and Python's bytecode directory point into it. Put
them somewhere you control:

```groovy
withEnv([
  'PYTHONUTF8=1',
  'PYTHONDONTWRITEBYTECODE=1',
  'PIP_DISABLE_PIP_VERSION_CHECK=1',
  "PIP_CACHE_DIR=${env.WORKSPACE}\\.pipcache",
]) {
  bat script: 'ci\\check.cmd', label: 'drift check'
}
```

`PYTHONUTF8=1` is the one to remember. UTF-8 mode makes Python ignore the
Windows code page for file and stdio encoding, and that removes the entire
class of "works on my machine, mojibake on the agent" problem with one
environment variable.

# The result

Two hundred and fourteen lines of PowerShell became forty-one lines of
PowerShell and about three hundred lines of Python. That's more code. It is
also code with sixty-one tests that run in four seconds on every push, a type
checker that found two bugs before it ran once, and a dependency set that's
identical on three machines.

The job itself got slower - building a virtual environment costs twenty
seconds - and it runs at ten past two in the morning, so I stopped caring
within a day.
