Best practices Richard Siddeway Powershell in depth
Powershell in depth translation.chapter 40.
This chapter contains: best practice for all occasions best practice for advanced scripts best practice for industrial use
Throughout this book, useful tips, practical tricks were given on how to ease your efforts, facilitate script support, speed up execution, and achieve greater flexibility. In this chapter, we collected our recommendations and organized them for convenient use. Our best recommendation is to use PowerShell every day. The following recommendations are not in order of importance. 40.1 PowerShell general best practices these recommendations are given to you to become better in powershell
Read the help system, it contains a lot of useful information, especially examples.
Use powershell 3 to do a task in the scheduler for regular help updates.
Set a script execution policy to at least RemoteSigned
Use conveyor. PowerShell is designed for use with pipeline. If you encode in the style of old scripting languages, you will lose most of the functionality and create yourself a lot of work.
Let variable names meaningful, for example, $ computer is better than $ x
Avoid names with spaces or special characters such as $ {computer}
Never set $ ErrorActionPreference (or $ VerbosePreference or any other “preference” variable) globally in a shell, script, or function. Instead, use parameters, such as -ErrorAction , or for the function parameter -Verbose , to set the parameter where required.
Avoid brute force collections — use ForEach-Object or ForEach , except when there is no other way to achieve the goal. (PowerShell doesn't like For-type constructions)
Use mostly single quotes if you do not need to substitute a variable or evaluate expressions within a string. If you work with SQL queries, remember that single quotes are used for strings and you need to specifically isolate or use double quotes.
Replacing strings, or animating is much easier than string concatenation.
Use built-in constants, PowerShell understands KB, MB, GB, TB and PB (built-in variables)
Avoid using native .NET classes and methods, except when there is no other alternative.
Be careful with the code downloaded from the Internet, always double check what the code does. Your environment may be different than the author’s environment and may cause many problems in your environment.
Filter early, format late! Do data sampling as soon as possible by reducing their volume, but format the data as late as possible, preferably just before displaying it.
')
40.2 best practices for advanced scripts
These recommendations are designed to write the best scripts.
Explicitly indicate the type of the variable, write [string] $ logfile
Assign variables to an explicit value after creation, if this variable is in this osprey. (easier - always initialize)
Give names to functions and threads in the style of gagol-action for example Get-DiskInfo
When a script that performs a task begins to be used before it is designed as a separate function, give the script file a name in the style of cmdlets, for example, Set-UserAttributes.ps1
Giving the name of the function or script in the form of a verb-noun add two or three letters of the prefix to the noun. This is usually abbreviated from the name of your organization. For example, for the company “great things” it could be GT , then the function name could look like Get-GTUserInfo or the script could be called Set-GTUserInfo.ps1
If you create private (non-exported) variables in a module, give these variables distinct names. Many developers use an underscore to highlight these names, such as $ _private or $ _counter .
When defining script parameters or functions, use the parameter names that match the parameter names of standard cmdlets that perform the same function. For example, the name of the -Computername parameter is preferable to -host or -machines, since is standard for cmdlets. You can always define an alias if you like it that way.
Avoid using Write-Host except when you need to display a message on the screen. If you are using Write-Host, use color highlighting or background color highlighting so your message will be highlighted on the screen.
Use [CmdletBinding] in your scripts and functions to use verbose, debugging, and advanced functionality.
If your function makes changes to the system, add support for -WhatIf and -Confirm
Use Write-Verbose to display the progress of the execution so that you can use this parameter to track where your function is going, or what it is doing now.
Use Write-Debug to display messages necessary for more successful debugging, remember that Write-Debug stops the execution of the script and gives you the opportunity to suspend its work.
Remember that Write-Warning exists for those cases when you need to display an informational message on the screen.
Scripts and functions must produce one and only one type of data at the output. Usually this is an object and it can be a specially designed type of object combining the properties of many different objects.
Always write help for your scripts and functions, even if it is based on comments. XML help is usually used if you need to do help in different languages.
Avoid changing aliases, variables, and other elements of a different scope than yours. (It turned out abstrusely. It's easier - do not change anything in other Osprey, in every possible way avoid it, otherwise you will get a code that is difficult to refactor and debug)
Separate the task into clear, small pieces according to their functionality and select each as a function. An example, a script that executes 10 different things should be split into 10 different functions, and the script should make calls to these functions in the right order.
Sign the code examples that you plan to distribute along with the script with your certificate if you plan to post it in public. Yes, this requires that you have a certificate for signing the code, for this you have to get it somewhere. But this is a good way for a public to check that your code has not been corrected by anyone.
Avoid using Hungarian notation in variable names. Conventions like $ strName or $ intCounter for powershell are obsolete and have no meaning. (easier - do not use the naming from the old school, just call it. There are no types in PowerShell as such, there is no need for Hungarian notation)
Use padding for code blocks such as {your code here} in contractions, your code will become readable.
Use Write-Verbose , Write-Debug, and similar inserts to document scripts and functions, use these constructions instead of inserting comments for the same purpose.
In scripts, functions, or workflow, avoid aliases (with the exception of common ones, such as Dir ) and abbreviations for parameter names. Write the full names of the parameters and cmdlets for better understanding and readability.
Avoid using the hyphen (`) at the end of the line to move the rest of the line to another line. Instead, break the line in a “natural” place. Make a line break after any of the following characters ({,; | these characters allow you to continue the current line from a new line.
If you use a proxy function, make sure that you publish it in your module.
Use the Test-Path and verify to them the existence of a folder and files.
Try..Catch ... Finally should be used wherever an exception can cause execution problems.
Keep the code logically simple , for example, avoid double negative in the if expression
Do not use Notepad as a script editor , with the exception of very simple actions. Use Powershell ISE. Notepad is suitable for quick viewing the code of small scripts, because notepad is the default editor
Avoid using the word return . Instead, think about how objects are transmitted along the conveyor . (there is a special chapter describing how to correctly pass the parameters. It is so specific for posed that it deserves a separate article)
40.3 best practices for industrial use These recommendations are designed for better use in the industrial environment.
Use group policies to distribute PowerShell remoting settings and script execution policies
Use remote connection and CIM sessions to access if there are more than one remote machines.
Use tasks (PowerShell jobs) if you need to perform long operations
Use workflows when you need scripts that can survive reboot, interrupt, or parallel computations.
Keep the scripts in the version control system, you will have a backup copy and you can return to the old version if necessary.
Restrict access to your scripts, only for those who need them.
Use Test-Connection to check the availability of the remote machine before you start working with it. (easier - check the availability of the host always)
Make sure that remoting is enabled on your servers.
Credits must be specified before they are used, do not create them in the code, especially if you need more than one. (easier - do not generate or store passwords in scripts, request them before use)
Use DCOM WS-MAN for CIM sessions if possible.
Develop standardized script templates, especially if the script is written by a team of administrators.
Set the AllSigned execution policy , use the code signature with a certificate from your PKI (later I will do a separate translation of the Security debate chapter)
Create a public script and define in it common functions, aliases, variables that your team may need. Store this script in a publicly accessible location accessible by UNC and then add it to your profile.
We hope that this is understandable without words. Test everything in a test environment . With modern virtualization capabilities, it's easy to do checks. You will not need any particularly expensive hardware, you can start with free VirtualBox or install a trial version of the product from Microsoft
Don Jones, Richard Siddaway. Powershell in depth. chapter 40.