Presentation is loading. Please wait.

Presentation is loading. Please wait.

PowerShell Scripting Best Practices in a Shared Environment

Similar presentations


Presentation on theme: "PowerShell Scripting Best Practices in a Shared Environment"— Presentation transcript:

1 PowerShell Scripting Best Practices in a Shared Environment
Dan Sheehan Sr. Premier Field Engineer

2 Important Shared Script Scenarios
Enterprise Environment - You get hit by a bus (or more typically get a new job). Others need to take over and maintain your code. You want to share your code. Others try to understand and learn from your code. You need revisit/update your old code. You have to re-familiarize and sometimes re-educate yourself. You want to optimize/enhance your code. Clean and organized code is easier to work with. I have been working and coding/scripting (using various technologies) in enterprise environments where code is shared, updated, and copied by others for over 20 years. This session focuses on best practices I find myself sharing and championing the most in shared environments (I include all enterprise environments). But before we try to do advanced things like improve speed up our script, it’s a good idea to review and implement coding best practices as a form of a code cleanup. Although some of these best practices can apply to any coding technology, they are all relevant to Windows PowerShell. The primary benefit of these best practices is to make it easier for others who review your script to understand and follow it. This is especially important for the ongoing maintenance of production scripts as people change jobs, get sick, or get hit by a bus (hopefully never). They also become important people and post scripts in online repositories, such as the TechNet Gallery, to share with the community.

3 *DO NOT ANALYZE THE CODE*
Before Best Practices *DO NOT ANALYZE THE CODE* No commenting, unclear variable names, random formatting.

4 After Best Practices 16 extra lines of “code” for comments.
The rest of the changes we will cover in this session and come back to this slide.

5 Topics Covered Keeping it simple. Using consistent indentation.
Use code logic controls. Variable naming methodology. Modifiable variable placement. Sufficient commenting. Unnecessary data output and retrieval. Leveraging comment based help.

6 Keep it Simple (Less is More)
Keep coding as linear and streamlined as possible. Avoid overcomplicating code without reason. Production code is not the place for learning a new coding style/technique. Will others in your environment be able to follow your code layout? Write (including formatting) for the lowest common denominator skillset. Example – Using Functions: Use Functions to reduce repeating the same code, or make code easily portable between scripts. Don’t create a Function just for the sake of creating it or organization. Alternative - PowerShell ISE 3+ Regions. Avoid calling Functions inside of other Functions (jumping around the script). The first best practice, which really applies to all coding, is to try to keep the script as simple and streamlined as possible. The first thing to remember is that most humans think in a very linear fashion, in this case from the top to the bottom of a script, so you want to try to keep your script as linear as possible. This means you should avoid making someone else jump around your script to try follow the logical outcome. Also during the course of learning how to do new and different things, IT workers have a tendency to make script more complex than it needs to be because that’s how some of us experiment with and learn new techniques. Even though learning how to do new and different things in Windows PowerShell scripting is important, learning exercises should be separate from production script that others will have to use and support. Function example: in the Mailbox Billing Report Generator script I wrote at a previous job, I used a function to generate Excel spreadsheets because I was going to be reusing that block of code in the script multiple times. It made more sense to have the code listed once and then called multiple times in the script. I also tried to locate the function close to the script where it was going to be called, so other people reviewing the script didn’t have to go far to find it. Ask yourself if the technique is adding value and functionality to the script and if it will potentially unnecessarily confuse another person reading it. Remember that just because you can use a certain technique doesn’t mean you should. Ultimately you need to write the script in the way that works best for you.

7 Use Consistent Indentation
Be consistent in your coding style overall. Indent every time you create a new construct (If condition, ForEach loop, etc.). Recommendation: Also indent code line wraps. NOTE: Different PowerShell editors use different indentations. Indenting should be cumulative and stacked: Along with keeping the script simple, it should be consistently organized and formatted, including indentations when new loop or conditional check code constructs are used. Lack of indentation, or even worse, inconsistent use of indentation makes script much harder to read and follow. One of the worst examples that I have seen is when someone pasted examples (including the example indentation level) from multiple sources into their script, and the indentation seemed to be randomly chosen. I had a really hard time following that particular script. Indentations should be used any time you have open and close curly braces around a block of code, so the person reading your script knows that block of code is a part of construct. This would apply to ForEach loops, Do…While condition check loops, or any block of code in between open and closing curly brackets of a construct. Indents can be used to show that a line of script is a continuation of the line above it. For example as a personal preference, whenever I use the back tick character ( ` ) to continue the same Windows PowerShell command on the next line in a script, I indent that next line so that as I am reviewing the script, I can easily tell that line is a part of the command on the previous line. Reference when to use tab indentations in example. Note that line #6 If condition causes another layer of indentation because it is inside of the If condition started on #2 and continued on #4.

8 Use Code Logic Controls
“:Name” loop label prefixes indicate script jump points. Example: :MailboxProcessing ForEach ($Mailbox in $GatheredMailboxes) { Explore processing controls. Break – Completely exits out of a loop/code block, abandoning remaining work. Label Support. Continue – Exits out of the current loop/code block, resuming remaining work. Label Support. Exit – Completely exits out of the script altogether. Careful with shell cut and paste… Return – Completely exits out of a function/script/or code block. Optionally passes value back to calling function. Provide alternatives to nested construct multi-layer “indent hell”. Use only after thorough testing. Exit in Shell closes the shell. I refer to excessive levels of nested indentation as “indent hell.” The script is so indented that the left half of the screen is wasted on white space and the real script is cramped on the right side of the screen. To avoid “indent hell,” consider using loop processing controls. Example nesting an If Condition check inside a ForEach loop. If the first two condition checks aren’t met, the Windows PowerShell script executes the Continue loop processing control, which tells it to skip the rest of the ForEach loop. If a label is used, script jumps to that specific point in the script versus just ending the loop.

9 Variable Naming Methodology
Clearly name variables. Verbose names are more easily understood later in the script and in future code review. Capitalize first character for each word to make it easier to read. $GatheredMailboxes versus $gatheredmailboxes. Avoid using unclear/ambiguous variable names such as “$i”. No performance benefit to skimping on variable name length. Use names relevant to the variable’s contents. $GatheredMailboxes indicates a collection of all gathered mailboxes: Variables should be clearly named for the data they represent. If the variable name contains multiple words, it’s a good idea to capitalize the first letter of each word so the name is easier to read because there are no spaces in a Windows PowerShell variable name. You may know the purpose of $i at the time you are writing the script, but don’t assume someone else will be able to pick up on their purposes when they are reviewing your script. Years from now, you may not remember the variable’s purposes when you are reviewing your script, and you will have to back track in your own script to reeducate yourself. Providing longer and more intelligently named variables does not adversely affect Windows PowerShell performance or memory utilization from what I have seen. So there should be no arguments for saving memory space or improving speed to impede the adoption of this practice. Building on this example, if we wanted to process each individual mailbox in the $GatheredMailboxes variable in a ForEach loop, we could additionally use a clear purpose variable with the name of $Mailbox

10 Modifiable Variable Placement
“Modifiable variables” refers to script variables that are intended to modify/customize in the future. Don’t make users work to find modifiable variables. Group modifiable variables together at the top of the script. Ideally, as the script is being written, but definitely before the script is “finished,” variables that are likely to be changed by a user in the future should be placed at the top of the script directly under the comment-based Help. This makes it easier for anyone making changes to those script variables, because they don’t have to go hunting for in your script. There are no concrete rules as to when you should place a variable at the top of a script or when you should leave it in the middle of the script. If you are unsure whether you should move the variable to the top, ask yourself if another person might want or need to change it in the future. When in doubt, and if moving the variable to the top of the script won’t break anything, it’s probably a good idea to move it

11 Comment, Comment, Comment…
Remember other users are reading the script. You may need to revisit it in the future. Always write your code as if you are going to publish it online. Over comment versus under comment. Can seem like overkill in the beginning. Not a popular concept.  Avoid “in-line” commenting at the end of PowerShell code line. There are different commenting styles. “#” for each line. “<#” and “#>” for a block of text. Indenting multiple lines of comments to show association. Writing functional script is important because, otherwise, what is the point of the script right? Writing script with consistent formatting and clearly labeled variables is also important, otherwise your script will be much harder to read and understand by someone else. Likewise adding detailed comments that explain what you are doing and why will further reduce confusion as other people (and your future self) try to figure out how and sometimes more importantly, why, specific code was used. When in doubt, I pretend I am going to publish the script in the TechNet Gallery (even if I know I won’t), and I use that as a gauge as to how much commenting to add. Most Windows PowerShell text editors will color code comments in a different color than the real script, so users who don’t care about the comments can skip them if they don’t need them. This level of detailed commenting of what you are doing and why can seem like overkill until you get into a habit of doing it. But it pays off in unexpected ways, such as not having to sit with a co-worker and explain your script step-by-step, or having to remember why a year ago you made an array called $MailboxesBothLimits. This is especially true if you are doing any complex work in the script that you have not done before, or you know others will have a hard time figuring it out. When it comes to inline commenting when comments are added on the same line of script but at the end, my advice is to strongly avoid this practice. When people skim script, they don’t always look to the end to see if there was a comment. Also, if others start modifying your script, you could end up with old or invalid comments in places where you didn’t expect them, which could cause further confusion.

12 Unnecessary Data Output and Retrieval
Storing data in file system slower than in-memory. Memory storage operates in nanoseconds. File actions operate in milliseconds. Inefficient - represents a disjointed two stage process. 2 operations (Out and In) are required. Subject to disk performance and associated dependencies (file system antivirus). Utilize in-memory alternatives. Data Tables. Arrays of PowerShell objects. Etc… Occasionally, I come across a script where the author is piping the results of one query to a file, such as a CSV file, and then later reading that file information back into the script as a part of another query. Although this certainly works as a method of temporarily storing and retrieving information, doing so takes the data out of the computer’s extremely fast memory (in nanoseconds) and slows down the process because Windows PowerShell incurs a file system write and read I/O action (in milliseconds). The more efficient method is to temporarily store the information from the first query in memory, for example, inside an array of custom Windows PowerShell objects or a data table, where additional queries can be performed against the in-memory storage mechanism. This skips the 2x file system I/O penalty because the data never leaves the computer’s fast memory where it was going to end up eventually. This may seem like a speed best practice, but keeping data in memory if at all possible avoids unnecessary file system I/O headaches such as underperforming file systems and interference from file system antivirus scanners.

13 Comment Based Help Also known as a PowerShell script “Header”.
Provides standard format for script information. Integrates into PowerShell’s native Help function. SYNOPSIS –a brief explanation of what the script or function does. DESCRIPTION – a more detailed explanation. PARAMETER name – an explanation of a specific parameter. EXAMPLE – an example of how to use the script or function. NOTES – any miscellaneous notes on using the script or function. LINK – a cross-reference to another help topic. Access with Get-Help as well as manual script review. Sometimes known as the “header” in Windows PowerShell scripts, a block of text called comment-based Help allows you to provide important information to readers in a consistent format, and it integrates into the Help function in Windows PowerShell. Specifically, if the proper tags are populated with information, and a user runs Get-Help YourScriptName.ps1, that information will be returned to the user. Although a header isn’t necessary for small scripts, it is a good idea to use the header to track information in large scripts, for example, version history, changes, and requirements. The header can also provide meaningful information about the script’s parameters. It can also provide examples, so your script users don’t have to open and review the script to understand what the parameters are or how they should use them.

14 Comment Based Help Example
Gallery Example: 56e2d037 If the –detailed or –full switches are used with the Get-Help cmdlet, even more information is returned

15 Write as if you are going to publish online!
SummarY Try to keep your code as simple as possible. Use standard and consistent formatting. Avoid “indent hell” with loop controls. Use clear and thoughtful variable names. Add sufficient commenting. Avoid temporary file system storage of data. Add comment based help to your scripts. Reminder – write as if you are going to publish online. Write as if you are going to publish online!

16 Additional Resources Shared Environment best practices deep dive reference: powershell-scripting-in-shared-environment.aspx Useful PowerShell websites: Hey Scripting Guy! – PowerShell focused blog with frequent examples and tips: Microsoft TechNet Gallery – Public code and script sharing repository: Microsoft Script Center – System Admin focused PowerShell resource: US/scriptcenter/ Scripting with PowerShell – TechNet documentation: Other PowerShell sessions in this track: PowerShell – Learn it, Use it, Love it :00 – 10:00AM PowerShell Tips and Tricks :25AM – 12:25PM Active Directory & PowerShell :30 – 2:30PM Introduction of Azure PowerShell Cmdlets 2:40 – 3:40PM I’ve got a PowerShell Secret: Putting a GUI on your Scripts 3:50 – 4:50PM

17 Please Join Us In Thanking Our Sponsors:

18 Please Connect with Your Education & User Community:
(Mobile-First, Cloud-First DC)

19 Hey Don’t Forget!!: Microsoft Careers is Onsite Today – Microsoft is hiring! The Microsoft Clinic is on 7th Floor, Room Sign-in and Connect with an SME for wide range of technologies Lunch is on the 7th Floor Break Area 12:30 Make Sure You Stay for the Raffle on the 7th Floor, Rooms 7023/7027/7032 Combined! Make sure you have all of the blocks on your raffle ticket stamped or signed

20 Microsoft Ignite May 4 – 8, 2015 Chicago, IL Spark the future.
The best and brightest minds will all be in one place to talk about cloud infrastructure and management, productivity, big data, and the internet of things, unified communications, mobility and more. Get ready for a glimpse of what’s possible today and in the future. Microsoft Exchange + Lync + MMS + Project + SharePoint + TechEd conferences = Microsoft Ignite May 4 – 8, 2015 Chicago, IL Register now

21 Get Social Social media is one of the best ways to keep up-to-date with the latest event news and buzz. Engage with Microsoft Ignite on the following channels: Like us and Share on Facebook Follow us, RT and engage on Twitter @MS_Ignite using #MSIgnite Connect via the Forum: Forum Follow us in the Office365 Ignite Event Group

22 Questions


Download ppt "PowerShell Scripting Best Practices in a Shared Environment"

Similar presentations


Ads by Google