Best practices Richard Siddeway Powershell in depth

    Powershell in depth translation. chapter 40.

    this chapter contains:
    best practice for all cases
    best practice for advanced scripts
    best practice for industrial use

    Throughout this book, useful tips and practical tricks have been given to ease your efforts, facilitate script support, speed up execution, achieve more flexibility. In this chapter, we have collected our recommendations and organized for convenient use. Our best recommendation is to use PowerShell every day. The recommendations below do not go in order of importance.

    40.1 PowerShell general best practices
    these guidelines are for you to become better at powershell
    • Read the help system, it contains a lot of useful information, especially examples.
    • Using powershell 3, do a task in the scheduler to update help regularly
    • Set script execution policy to at least RemoteSigned
    • Use the conveyor. PowerShell is designed for use by the conveyor. If you code in the style of old scripting languages, you will lose most of the functionality and create yourself a lot of work.
    • Give meaningful names to variables, for example $ computer is better than $ x
    • Avoid names with spaces or special characters such as $ {computer}
    • Never set the $ ErrorActionPreference variable (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 it is required.
    • Avoid using enumeration of collections - using ForEach-Object or ForEach , except when there is no more way to achieve the goal differently. (PowerShell doesn't like For type constructs)
    • Use mostly single quotes if you don't need to do variable substitution or evaluate expressions inside a string. If you are working with SQL queries, then remember that single quotes are used by him for strings and you need to specifically isolate or apply double quotes.
    • String replacement, or animation, is much simpler 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 unless there is no other alternative
    • Be careful with 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! Sample the data as early as possible, reducing its size, but format the data as late as possible, best of all just before being displayed.


    40.2 best practice for advanced scripts
    • These guidelines are for writing the best scripts.
    • Indicate explicitly the type of variable, write [string] $ logfile
    • Assign the variables an explicit value after creation, if this variable is in this array. (easier - always initialize)
    • Give names to functions and streams in the style of gagol-action for example Get-DiskInfo
    • When the script performing the 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 short for the name of your organization. For example, for “great things” company 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-exportable) 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 the parameters of a script or function, use the parameter names that match the parameter names of standard cmdlets that execute the same functions. For example, the parameter name -Computername is preferable to -host or -machines, because is standard for cmdlets. You can always determine the alias if you like it.
    • Avoid using Write-Host unless you want the message to appear on the screen. If you use 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 execution progress so that you can use this parameter to track where your function is executing or what it is doing right now.
    • Use Write-Debug to display the messages necessary for more successful debugging, remember that Write-Debug stops the execution of the script and makes it possible 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 should produce one, and only one data type at the output. Usually this is an object and it can be a specially designed type of object that combines the properties of many different objects.
    • Always write help for your scripts and functions, even if it's comment based help. 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 your scope. (it turned out to be abstruse. easier - do not change anything in other osprey, avoid this in every way; otherwise, you will get code that is difficult to refactor and debug)
    • Divide the task into clear, small pieces according to their functionality and select each as a function. For example, a script executing 10 different things should be broken down into 10 different functions, and the script should make calls to these functions in the desired sequence.
    • Sign code examples that you plan to distribute with the script your certificate, if you plan to put it in public. Yes, this requires you to have a certificate to sign the code, for this you will 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 deprecated and have no meaning. (easier - don’t use naming from the old school, just name it. There are no types as such in PowerShell, no Hungarian notation needed)
    • Use padding for code blocks such as {your code here} in the instructions, your code will become readable
    • Use Write-Verbose , Write-Debug and similar inserts to document scripts and functions, use these constructs instead of inserting comments for the same purpose.
    • In scripts, functions, or workflows, avoid aliases (with the exception of common Dir for example ) and parameter name abbreviations. Write fully parameter names and cmdlets for better understanding and readability.
    • Avoid using the hyphen (`) character at the end of a line to wrap the rest of the line. Instead, break the line in a "natural" place. Do a line break after any of the following characters ({,; | these characters allow you to continue the current line with a new line.
    • If you use function proxies, make sure you publish it in your module
    • Use Test-Path and verify that the folder and files exist.
    • Try..Catch ... Finally should be used wherever an exception can cause execution problems
    • Keep the code logically simple , for example, avoid the double negative in the if expression
    • Do not use notepad as a script editor , except for very simple actions. Use Powershell ISE. Notepad is suitable for quickly viewing the code of small scripts, as notepad is the default editor
    • Avoid using the word Return . Instead, think about how objects are conveyed through the pipeline . (there is a special chapter describing how to pass parameters correctly. So specific thing for a posh that deserves a separate article)


    40.3 best practice for industrial use
    These guidelines are for best use in an 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 machine.
    • Use tasks (PowerShell jobs) if you need to perform long operations
    • Use workflows when you need scripts that can survive reboots, interrupts or parallel computing
    • Store the scripts in the version control system, you will have a backup copy and you can return to the old version if necessary.
    • Limit 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 - always check host availability)
    • Make sure PowerShell remoting is enabled on your servers.
    • Loans must be set 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 scripts are written by an admin team.
    • Set the AllSigned execution policy , use the code signing 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 public place 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 do not need any particularly expensive equipment, you can start with the free VirtualBox or install the trial version of the product from Microsoft


    Don Jones, Richard Siddaway. Powershell in depth. chapter 40.

    Also popular now: