What is the recommended coding style for PowerShell?
- by stej
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.