-
Notifications
You must be signed in to change notification settings - Fork 0
Powershell Coding Standards
Nigel Tatschner edited this page Sep 16, 2019
·
2 revisions
Agree on code line length
115 characters? Use Splatting where possible Try using the following to split your lines ( “String Data” +)
PowerShell uses PascalCase (Capital letter on each word), I think we should follow suit.
Be descriptive with variable names but not verbose Script global variable definitions should always be at the top of the script
Avoid hard coding data Use Param() where possible (allows re-usability) Avoid Generic Types ([Object]) if you know what data you should expect
Open Brace at end of line and close at start of line
- Layout code to follow a logical execution path
- Start with the param() block or #Requires statement
- Use Begin {}, Process {}, End {} (Even if you don’t use them, this makes it easier to extend
- White Spaces, Blank lines and Trailing spaces
- 2 blank lines between functions
- 1 at the end of file
- Use for readability but lines maybe omitted if line content is closely related
- Sub-expressions and script blocks should have a single space at the start and end
- Don’t use ‘Return’ to pass an object back – Simply reference the object
- Only return objects in the ‘Process’ block
- Define your output type [OutputType( [String],ParameterSetName = ‘Default’ )]
- Avoid validating parameters in the body of the script/function, use the validation attributes in the param block
- Use the full cmdlet name
- Avoid aliases
- Avoid positional parameter usage, use parameter name
- Keep it readable
- Use function help blocks when possible
- Use inline comments only if it’s not obvious what that line dose
- Always write help for your script/functions
- Remember your not going to be the only person using the code
- You have different understanding of how the code works, use explicit language
- Verb-Noun for functions and scripts that have parameterized inputs
- Avoid Clobber
- For private functions Use Verb-(Creator initials)Noun this will give us an idea of who initially created the command outside of the help and comments
- Try and break down long functions in to smaller segments
- Make them do one thing well
- Functions inside functions is acceptable if it makes sense to the code
- Make it modular
- Make it reusable
- Try not to use Write-Host
- Add Write-Verbose to give extra status information about a running command
- Write-Progress to give progress information when needed to be run interactively
- Use Write-Debug to give the code maintainer extra information
- Use -ErrorAction ‘Stop’ in Try Catch blocks
- Always Use Try {} Catch {} for every command that could fail, providing termination or handling the error and remember to output errors to the error stream