Is there any recommended coding style how to write PowerShell scripts? It's not about how to structure the code (how many functions, if to use module, ...). It's about 'how to write the code so that it is readable'.
In programming languages there are some recommended coding styles (what to indent, how to indent - spaces/tabs, where to make new line, where to put braces,...), but I haven't seen any suggestion for PowerShell.
What I'm interested particularly in:
How to write parameters
function New-XYZItem
( [string] $ItemName
, [scriptblock] $definition
) { ...
(I see that it's more like 'V1' syntax) or
function New-PSClass {
param([string] $ClassName
,[scriptblock] $definition
)...
or (why to add empty attribute?)
function New-PSClass {
param([Parameter()][string] $ClassName
,[Parameter()][scriptblock] $definition
)...
or (other formatting I saw maybe in Jaykul's code)
function New-PSClass {
param(
[Parameter()]
[string]
$ClassName
,
[Parameter()]
[scriptblock]
$definition
)...
or ..?
How to write complex pipeline
Get-SomeData -param1 abc -param2 xyz | % {
$temp1 = $_
1..100 | % {
Process-somehow $temp1 $_
}
} | % {
Process-Again $_
} |
Sort-Object -desc
or (name of cmdlet on new line)
Get-SomeData -param1 abc -param2 xyz |
% {
$temp1 = $_
1..100 |
% {
Process-somehow $temp1 $_
}
} |
% {
Process-Again $_
} |
Sort-Object -desc |
and what if there are -begin -process -end params? how to make it the most readable?
Get-SomeData -param1 abc -param2 xyz |
% -begin {
init
} -process {
Process-somehow2 ...
} -end {
Process-somehow3 ...
} |
% -begin {
} ....
or
Get-SomeData -param1 abc -param2 xyz |
% `
-begin {
init
} `
-process {
Process-somehow2 ...
} `
-end {
Process-somehow3 ...
} |
% -begin {
} ....
the indentitation is important here and what element is put on new line as well.
I have covered only questions that come on my mind very frequently. There are some others, but I'd like to keep this SO question 'short'.
Any other suggestions are welcome.
After spending a couple years diving pretty deep into Powershell v2.0, here's what I've settled on:
Oops, that got longer than I expected. Hope the answers you wanted are in there somewhere :)
edit - StackOverflow's syntax highlighter is giving up on me completely. Paste it into the ISE.
I recently came across an excellent point about indent style in PowerShell. As the linked comment states, observe the difference between these same syntaxes:
and
While my inclination is to "do as the Romans do" and use the standard C# indentation style (Allman, more or less), I take issue with this exception and others similar to it.
This inclines me personally to use my favored 1TBS, but I could be convinced otherwise. How did you settle, out of curiosity?
For the record, there is also The PowerShell Best Practices and Style Guide.
It is far from official, but has several good points.