Best practices Richard Siddeway Powershell in depth
this Chapter contains:
the best practice for all occasions
best practices for advanced scripting
best practices for industrial use
Throughout this book were given useful tips and practical tricks how to ease your efforts to facilitate the scripting, accelerate performance, achieve greater flexibility. In this Chapter, we have collected our recommendations and arranged 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
the recommendations given to you to become better at powershell
the
-
the
- Read built-in help system, it contains a lot of useful information, especially the examples. the
- Using powershell 3 to do the task in the scheduler for regular update help the
- Set the execution policy of scripts at least RemoteSigned the
- , Use the conveyor. PowerShell is designed for use with a conveyor. If you will encode in the style of old scripting languages you will lose most of the functionality and create yourself a lot of work. the
- Let variable a meaningful name, such as $computer better than $x the
- avoid names with spaces or special characters such as ${computer} the
- Never set the variable $ErrorActionPreference (or $Variable or any other "preference" variable) globally in the shell, script or function. Instead, use parameters such as -ErrorAction, or function -Verbose, for a parameter setting where required. the
- avoid using too much collections — the use of ForEach-Object or ForEach, except when there are no more ways for another to achieve the goal. (PowerShell does not like constructs like 'For')
- Replace strings, or animation much easier than string concatenation. the
- Use built-in constants, PowerShell understands KB, MB, GB, TB and PB (built-in variable) the
- avoid using native .NET classes and methods, except when no other alternatives the
- Be careful with code downloaded from the Internet, always double check what the code does. Your environment may be different than the environment of the author and may cause in your environment a lot of problems. the
- Filters early, formoterol later! Do the sample data as early as possible to reduce their volume, but formatiraj data as late as possible, preferably directly in front of the display.
mainly Use single quotes if you don't need to do variable substitution or to evaluate expressions inside strings. If you rabotaete with the SQL queries then remember that single quotes are used for strings and you need to do isolation or use double quotes. the
40.2 best practices for advanced scripting
the
- clearly Indicate the type of a variable, write [string]$logfile the
- Privavy clear variable value after it is created, if this variable in this scope. (easier — initializers always) the
- Let the names of functions and flows in the style of Gaga-action for example Get-DiskInfo the
- When the script executes the task begins to be used before will be executed in a separate function, give the script file name in the style cmdlets, such as Set-UserAttributes.ps1 the
- Giving the name of the function or script in the form verb-noun, add two or three letter prefix to the noun. This is usually the abbreviation of your organization. For example, the company "great things" it may be GT, then the function name would look like Get-GTUserInfo or the script would be called Set-GTUserInfo.ps1 the
- If you create a private (non-exported) variables in a module, divide these variables distinct names. Many developers use an underscore to highlight these names, such as $_private or $_counter. the
- Avoid to use Write-Host unless you need to get the message is on the screen. If you use Write-Host, use color coding or highlighting background color so your message will be highlighted on the screen. the
- Use [CmdletBinding] in your scripts and functions to use verbose, debugging and advanced functionality. the
- If your function makes changes in the system, add support for -WhatIf and Confirm the
- Use Write-Verbose to display progress, you can use this option to monitor in what place is the implementation of your function, or what she's doing now. the
- Use Write-Debug to output 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. the
- Remember that Write-Warning exists for those occasions when you need to display an informational message on the screen
- Always write help for your scripts and functions, even if this help is based on the review. The XML reference is typically used if you need to make reference in different languages. the
- avoid to change the aliases, variables, and other elements of a different scope than your area. (technical and confusing happened. easier — don't change anything other ospreys, to avoid this otherwise you will get the code difficult to refactor and debug)
- Podpisyvat code examples that you plan to distribute along with the script with this certificate if you plan to put it on the public. Yes it requires you have a certificate for code signing, it will have somewhere to receive it. But this is a good way for the public to check that your code has not been tampered with by someone. the
- avoid using Hungarian notation in variable names. Agreement type $strName or $intCounter for powershell are outdated and make no sense. (simpler does not use the naming from the old school, just call. In PowerShell there are no types as such, there is no need for Hungarian notation) the
- Use indentation for blocks of code such as { your code here } in the structures, your code will be readable the
- Use Write-Verbose, Write-Debug and the like insertion to document scripts and functions, use these designs instead of inserting comments for the same purpose. the
- In scripts, functions or workflow avoid aliases (except common such as Dir), and abbreviations of parameter names. Write all the names of the parameters and cmdlets for better understanding and readability. the
- avoid using the hyphen character (`) at the end of the row to migrate the rest of on the line. Instead, the interrupt line in the "natural" place. Do the line breaks after any of the following characters ( {,; | these characters are allowed to continue the current line with a new line. the
- If you use proxy functions, make sure that you published it in your module the
- Use the Test-Path them and check the existence of folder and files
- do Not use Notepad as the script editor, except for very simple actions. Use Powershell ISE. Notepad is good for quick viewing of code small scripts, because Notepad is the default editor
These guidelines are created for writing the best scripts the
Scripts and functions should produce one and only one data type in the output.Usually is an object and it can be a specially designed object obyedinyaet the properties of many different objects. the
Separate the task into precise, small chunks of their functionality and highlight each in the form of functions. Example script performs 10 different things that should be split into 10 different functions, and the script needs to do calls to these functions in the correct sequence. the
Try..Catch...Finally should be used everywhere where an exception can cause problems of performance
Keep code logically simple, for example, avoid double negatives in if the
40.3 best practices for industrial use
These recommendations are made for best use in an industrial environment.
the
-
the
- Use group policy to distribute settings PowerShell remoting and the policy of execution of scripts the
- Use a remote connection, and CIM session for accessing remote machines if more than one. the
- Use the task (PowerShell jobs) if you need to perform long operations the
- Use workflows when you need scripts that are able to survive the restart, abort, or parallel computing the
- Store the scripts in the version control system, you will have the backup and you will be able to go back to an older version if necessary. the
- Limit the access to your scripts, only for those who needs them. the
- Use the Test-Connection to check the availability of the remote machine before you start working with her. (simple — check the availability of the host always) the
- make Sure that PowerShell remoting enabled on your servers. the
- Creditly must be specified before will be used, do not create them in code, especially if you need more than one. (simpler does not generate and don't save passwords in scripts, request them before use) the
- Use DCOM WS-MAN CIM sessions if possible. the
- Develop standardized templates scripts especially if the script writes a team of administrators. the
- Set the execution policy AllSigned, use a code signing certificate from your PKI (I'll do a separate translation of the head of the Security debate) the
- Create a public script and define its General functions, aliases, variables that may need your team. Store this script in a public place, available at UNC and then add it to your profile.
We hope this goes without saying. Test all in a test environment. With modern virtualization capabilities was just to do background checks. You don't need some piece of particularly expensive equipment, you can start with the free VirtualBox, or install the trial version of Microsoft
Don Jones, Richard Siddaway. Powershell in depth. Chapter 40.
Комментарии
Отправить комментарий