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.
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 a 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
, and -end
parameters? How do I 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 indentation 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 Stack Overflow question 'short'.
Any other suggestions are welcome.