PowerShell Scripting Best Practices in a Shared Environment

Slides:



Advertisements
Similar presentations
Building a Career Portfolio
Advertisements

Business Development Suit Presented by Thomas Mathews.
MICHAEL MARINO CSC 101 Whats New in Office Office Live Workspace 3 new things about Office Live Workspace are: Anywhere Access Store Microsoft.
P5, M1, D1.
1 Working with Social Media in Research Settings Victoria Wade Careers Consultant.
JavaScript Libraries for SharePoint February 21 st, 2015 Timothy Ferro.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
CSC 101 Slide Show Ashley Carroll. Podcast What is Podcasting? Podcasting is the distribution of audio or video files, such as radio programs or music.
Developing a Basic Web Page with HTML
Web Searching. Web Search Engine A web search engine is designed to search for information on the World Wide Web and FTP servers The search results are.
The University of Adelaide Table Talk: Using tables in Word Peter Murdoch March 2014 PREPARING GOOD LOOKING DOCUMENTS.
Open and save files directly from Word, Excel, and PowerPoint No more flash drives or sending yourself documents via Stop manually merging versions.
Using Blogs for Legal Research and Practice Development Raizel Liebler Reference Librarian John Marshall Law Library.
An Introduction to Content Management. By the end of the session you will be able to... Explain what a content management system is Apply the principles.
Web 2.0: Concepts and Applications 2 Publishing Online.
Creating a Simple Page: HTML Overview
Westwood Jr./Sr. High School Westwood Jr./Sr. High School 701 Ridgewood Road Twp. of Washington, NJ We are pleased to introduce Family.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Hello AP Computer Science!. What are some of the things that you have used computers for?
The Writing Process Introduction Prewriting Writing Revising
SOCIAL NETWORKS AND THEIR IMPACTS ON BRANDS Edwin Dionel Molina Vásquez.
1 Web Developer & Design Foundations with XHTML Chapter 13 Key Concepts.
Lecturer: Ghadah Aldehim
Arif Fazel School of Molecular and Cellular Biology Academic Advisor IlliAAC Conference 2012 December 14, 2012 Tweet Us, Like Us, Watch US! MCB Goes Viral.
© 2003 East Collaborative e ast COLLABORATIVE ® eC SoftwareProducts TrackeCHealth.
Microsoft ® Official Course Module XA Using Windows PowerShell ®
Office Live Workspace Visio 2007 Outlook 2007 Groove 2007 Access 2007 Excel 2007 Word 2007.
In addition to Word, Excel, PowerPoint, and Access, Microsoft Office® 2013 includes additional applications, including Outlook, OneNote, and Office Web.
Knowing Your Facebook From Your Flickr Dan O’ Neill – -
Appendix A Starting Out with Windows PowerShell™ 2.0.
1 In the good old days... Years ago… the WWW was made up of (mostly) static documents. –Each URL corresponded to a single file stored on some hard disk.
Design and Construction of Accessible Web Sites Michael Burks Chairman Internet Society SIG For Internet Accessibility for People with Disabilities June.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
BTEC Unit 06 – Lesson 08 Principals of Software Design Mr C Johnston ICT Teacher
Paul Mundy Editing step by step How an expert does it.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Content Manager User Meeting January 24, CMA User Group Agenda  Introductions, Welcome Jennyl Simon  SharePoint  Michigan.gov Status  Pure Michigan.
Good Practice Conference “…collating, disseminating and encouraging the adoption of good practice…”
Chapter 6 Server-side Programming: Java Servlets
OT Connections is AOTA’s new online community which allows occupational therapists, occupational therapy assistants and students to connect with each.
Digital Collaboration By Kathleen Kass 4b Due by October 15, 2014.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Online Conference June 17 th and 18 th SharePoint Online Administration with PowerShell.
1 UNIT 13 The World Wide Web Lecturer: Kholood Baselm.
Coding Conventions  Coding conventions are a set of guidelines for a specific software project that recommend programming style, practices and methods.
Transportation Agenda 165. Transportation About Pages Pages organize and present information Pages are files that end in.aspx 166.
+ Publishing Your First Post USING WORDPRESS. + A CMS (content management system) is an application that allows you to publish, edit, modify, organize,
CHAPTER 5 Introduction to Word Processing. OBJECTIVES 1.Define common terms related to word processing 2.Create, format, edit, save, and print Microsoft.
INTRODUCTION TO COMPUTER PROGRAMMING(IT-303) Basics.
3 Apps for Primary Teachers to Organize Center Activities iPossibilities Conference – June 10, 2014 Amanda Hanna
Integrating and Extending Workflow 8 AA301 Carl Sykes Ed Heaney.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
How to create a Windows app with Project Siena, SharePoint and Office 365 Knut Relbe-Moe Office 365 MVP Chief Technical Architect.
1 UNIT 13 The World Wide Web. Introduction 2 Agenda The World Wide Web Search Engines Video Streaming 3.
1 UNIT 13 The World Wide Web. Introduction 2 The World Wide Web: ▫ Commonly referred to as WWW or the Web. ▫ Is a service on the Internet. It consists.
ICAD3218A Create User Documentation.  Before starting to create any user documentation ask ‘What is the documentation going to be used for?’.  When.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Productivity Architect Meet Chris Bortlik Author, Blogger, Speaker.
Take Your Data Analysis and Reporting to the Next Level by Combining SAS Office Analytics, SAS Visual Analytics, and SAS Studio David Bailey Tim Beese.
Multiprogramming. Readings r Chapter 2.1 of the textbook.
COPS Digital Expansion Project
MyWritingLabPlus and the Research Paper
Topics Introduction to File Input and Output
PowerShell Best Practices for SQL DBA’s
Chapter 5 Microsoft Excel Window
Site scripts and Site Design
Deep Dive into Azure API Apps and Logic Apps
Topics Introduction to File Input and Output
Presentation transcript:

PowerShell Scripting Best Practices in a Shared Environment Dan Sheehan Sr. Premier Field Engineer Daniel.Sheehan@Microsoft.com

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.

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

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.

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.

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.

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.

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.

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

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

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.

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.

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.

Comment Based Help Example Gallery Example: https://gallery.technet.microsoft.com/Get-Object-Group- 56e2d037 If the –detailed or –full switches are used with the Get-Help cmdlet, even more information is returned

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!

Additional Resources Shared Environment best practices deep dive reference: http://blogs.technet.com/b/heyscriptingguy/archive/2014/05/17/weekend-scripter-best-practices-for- powershell-scripting-in-shared-environment.aspx Useful PowerShell websites: Hey Scripting Guy! – PowerShell focused blog with frequent examples and tips: http://blogs.technet.com/b/heyscriptingguy/ Microsoft TechNet Gallery – Public code and script sharing repository: https://gallery.technet.microsoft.com/ Microsoft Script Center – System Admin focused PowerShell resource: https://technet.microsoft.com/en- US/scriptcenter/ Scripting with PowerShell – TechNet documentation: https://technet.microsoft.com/en-us/library/bb978526.aspx Other PowerShell sessions in this track: PowerShell – Learn it, Use it, Love it. 9:00 – 10:00AM PowerShell Tips and Tricks. 11:25AM – 12:25PM Active Directory & PowerShell 1: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

Please Join Us In Thanking Our Sponsors:

Please Connect with Your Education & User Community: http://www.meetup.com/MFCF-DC/ (Mobile-First, Cloud-First DC)

Hey Don’t Forget!!: Microsoft Careers is Onsite Today – Microsoft is hiring! The Microsoft Clinic is on 7th Floor, Room 7063 - 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

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 http://ignite.microsoft.com

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 http://www.facebook.com/MicrosoftIgnite Follow us, RT and engage on Twitter @MS_Ignite using #MSIgnite Connect via the Forum: http://channel9.msdn.com/Forums/MicrosoftIgnite Forum Follow us in the Office365 Ignite Event Group https://www.yammer.com/itpronetwork/#/threads/inGroup?type=in_group&feedId=4589545

Questions