This is how I write PowerShell scripts. I use full cmdlet names, full argument switch names, and I even specify argument switches to positional arguments. I also do my best to honor common flags like `-WhatIf`, `-Verbose`, and `-ErrorAction`. So I end up with scripts like this:
if (-not $(Test-Path -Path "$Path" -PathType Container)) {
Write-Error -Message "Path ($Path) does not exist or is not a directory." -Category InvalidArgument;
return;
}
When you do this properly, it feels like magic. For example, I wrote a script that does local Maven and Docker builds for a bunch of related projects. So I wrote two functions `Build-Maven` and `Build-Docker` with proper common flag support and error handling. Then, when I use them, I just do something like this:
$PSDefaultParameterValues = @{
'Build-Maven:ErrorAction' = 'Stop';
'Build-Docker:ErrorAction' = 'Stop';
};
Build-Maven "$Path\A";
Build-Maven "$Path\B";
Build-Docker -Path "$Path\B" `
-Dockerfile "$Path\B\Dockerfile" `
-Tag "B:$Tag";
That first clause automatically amends `Build-Maven` and `Build-Docker` commands with `-ErrorAction Stop`. So if any of those build commands fail, the entire script halts there. And, if I pass in `-Verbose` to this script, that's forwarded to the build commands and I'll see the Maven and Docker build output.