Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

PowerShell Troubleshooting Guide
PowerShell Troubleshooting Guide
PowerShell Troubleshooting Guide
Ebook362 pages2 hours

PowerShell Troubleshooting Guide

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Windows PowerShell provides an amazing platform for administrative scripting and automation. Understanding the PowerShell language will enable you to spend less time troubleshooting and be more effective when debugging is required. PowerShell also includes several avenues to provide feedback from your code that will make your troubleshooting and debugging time more profitable.

Improved coding practices combined with useful diagnostic information can lead to results quickly. This book starts with background information on the purposes of automation and PowerShell's entrance into Microsoft's automation strategy, and also answers the question of whether scripting (and specifically PowerShell scripting) is essentially different than traditional programming. A brief overview of the main features of the PowerShell language along with examples is provided. Focus is placed on proper script design and use of PowerShell features in an attempt to reduce the need for troubleshooting.

LanguageEnglish
Release dateNov 28, 2014
ISBN9781782173588
PowerShell Troubleshooting Guide
Author

Michael Shepard

Michael Shepard has been working with computers since the early 1980s, starting with an Apple II at school and a Commodore 64 at home. He first worked in IT in 1989 and has been a full-time professional in this field since 1997. He has been working at Jack Henry and Associates since 2000. Mike's focus has changed over the years from being a database application developer to a DBA (an application administrator), and he is now a solutions architect. In his years as a DBA, he found PowerShell to be a critical component in creating the automation required to keep up with a growing set of servers and applications. He is active in the PowerShell community on StackOverflow and in the projects on CodePlex. He has been blogging about PowerShell since 2009 at https://powershellstation.com and is the author of PowerShell Troubleshooting Guide by Packt Publishing.

Related to PowerShell Troubleshooting Guide

Related ebooks

Enterprise Applications For You

View More

Related articles

Reviews for PowerShell Troubleshooting Guide

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    PowerShell Troubleshooting Guide - Michael Shepard

    Table of Contents

    PowerShell Troubleshooting Guide

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why subscribe?

    Free access for Packt account holders

    Instant updates on new Packt books

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. PowerShell Primer

    Introduction

    Cmdlets

    The big three cmdlets

    Functions

    Scripts

    Pipelines

    How pipelines change the game

    What's the fuss about sorting?

    Variables

    Modules

    Further reading

    Summary

    2. PowerShell Peculiarities

    PowerShell strings

    String substitution

    How string substitution goes wrong

    Escaping in PowerShell strings

    Function output

    Pipeline processing

    PowerShell error handling

    The trap statement

    try, catch, and finally statements

    Non-terminating errors

    Further reading

    Summary

    3. PowerShell Practices

    Filter left

    Format right

    Comment-based help

    Using Write-* cmdlets

    Write-Host

    Output – the correct way

    What about the other Write-* cmdlets?

    Which Write should I use?

    Write-Verbose

    Write-Debug

    Write-Warning

    Write-Error

    Write-Progress

    Further reading

    Summary

    4. PowerShell Professionalism

    Naming conventions

    Cmdlet and function naming

    Parameter naming

    Module naming

    Variable naming

    Modularization

    Breaking a process into subtasks

    Helper functions

    Single responsibility principle

    Don't repeat code

    Understanding the process

    Version control

    Using version control with PowerShell

    Unit testing

    Rolling your own unit tests

    Why is PowerShell testing difficult?

    An introduction to Pester

    Mocking with Pester

    Further reading

    Summary

    5. Proactive PowerShell

    Error handling

    Error-handling guidelines

    Error-handling techniques

    Investigating cmdlet error behavior

    Catch and release

    CmdletBinding()

    Common parameter support

    SupportsShouldProcess

    Parameter name validation

    Parameter value validation

    Pipeline input

    Pipelines and function execution

    Parameter type transformation

    #REQUIRES statements

    Set-StrictMode and Set-PSDebug -strict

    Further reading

    Summary

    6. Preparing the Scripting Environment

    Validating operating system properties

    Workstation/server version

    Operating system version

    Putting it all together

    Validating service status

    Validating disk and memory availability

    Validating network connectivity

    Using telnet

    Using Test-NetConnection

    Writing Test-NetConnection in downstream versions

    Testing UDP and ICMP connectivity

    Validating connectivity prior to implementation

    Putting it all together

    Further reading

    Summary

    7. Reactive Practices – Traditional Debugging

    Reading error messages

    The color problem

    Changing console colors

    Changing ISE colors

    PowerShell profiles

    Error message content

    Using Set-PSDebug

    Debugging in the console

    Debugging in the ISE

    Event logs

    Listing event logs

    Reading event logs

    Writing to event logs

    The PSDiagnostics module

    Using –confirm and –whatif

    Reducing input set

    Using Tee-Object to see intermediate results

    Replacing the foreach loop with the foreach-object cmdlet

    Further reading

    Summary

    8. PowerShell Code Smells

    Code smells

    Code smells, best practices, antipatterns, and technical debt

    Language-agnostic code smells

    PowerShell-specific code smells

    Missing Param() statements

    Homegrown common parameters

    Unapproved verbs

    Accumulating output objects

    Sequences of assignment statements

    Using untyped or [object] parameters

    Static analysis tools – ScriptCop and Script Analyzer

    ScriptCop

    Script Analyzer

    Further reading

    Summary

    Index

    PowerShell Troubleshooting Guide


    PowerShell Troubleshooting Guide

    Copyright © 2014 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: November 2014

    Production reference: 1211114

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78217-357-1

    www.packtpub.com

    Cover image by Michal Jasej (<milak6@wp.pl>)

    Credits

    Author

    Michael Shepard

    Reviewers

    Christian Droulers

    Rob Huelga

    Steve Shilling

    Acquisition Editor

    Meeta Rajani

    Content Development Editor

    Adrian Raposo

    Technical Editors

    Tanvi Bhatt

    Pragnesh Billimoria

    Copy Editors

    Simran Bhogal

    Maria Gould

    Ameesha Green

    Project Coordinator

    Kinjal Bari

    Proofreaders

    Simran Bhogal

    Joel T. Johnson

    Indexer

    Monica Ajmera Mehta

    Production Coordinator

    Alwin Roy

    Cover Work

    Alwin Roy

    About the Author

    Michael Shepard has been working with computers since the early '80s, starting with an Apple II in school and a Commodore 64 at home. He started working in the IT industry in 1989 and has been working full-time since 1997. He has been working at Jack Henry & Associates, Inc. since 2000. His focus has changed over the years from being a database application developer to a DBA, an application admin, and is now a solutions architect. In his years as a DBA, he found PowerShell to be a critical component in creating the automation required to keep up with a growing set of servers and applications. He is active in the PowerShell community at Stack Overflow and projects at CodePlex. He has been blogging about PowerShell since 2009 at http://powershellstation.com.

    I'd like to thank my employer, Jack Henry & Associates, Inc., for allowing me the freedom over the last few years to both learn and teach PowerShell. My wonderful wife, Stephanie, and my children, Simeon and Gwen, also deserve thanks for humoring me when I can't stop talking about PowerShell, and for giving me some breathing room to write.

    About the Reviewers

    Christian Droulers is a late-blooming software developer. He only started programming in college and has not stopped since. He's interested in beautiful, clean, and efficient code.

    Steve Shilling has worked in the IT industry commercially since 1987, but started with computers in 1982 writing BASIC programs and debugging game programs written by others. He has broad knowledge about Unix, Windows, and Mainframe systems. He primarily lives in the Unix/Linux world automating systems for deployments and businesses, and has spent many years working in system administration, software development, training, and managing technical people. He remains in the technical field of expertise providing knowledge and experience to companies around the world to make their systems stable, reliable, and delivered on time. His experience has taken him through many different industries covering banking and finance, insurance services, betting exchanges, TV and media, retail, and others, allowing him to have a unique perspective of IT in business where most have only worked in one industry.

    Steve works for TPS Services Ltd., which specializes in IT training and consultancy, life coaching, management training, and counselling. The IT part of TPS Services Ltd. specializes in Linux/Unix systems for small, medium, and large organizations, and the integration of Linux and Windows systems.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Instant updates on new Packt books

    Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

    Preface

    PowerShell Troubleshooting Guide uses easy-to-understand examples to explain the PowerShell language, enabling you to spend more of your time writing code to solve the problems you face and less time agonizing over syntax and cryptic error messages. Beginning with the foundations of PowerShell, including functions, modules, and the pipeline, you will learn how to leverage the power built into the language to solve problems and avoid reinventing the wheel. Writing code in PowerShell can be fun, and once you've learned the techniques in this book, you will enjoy PowerShell more and more.

    What this book covers

    Chapter 1, PowerShell Primer, provides a brief introduction to some of the most important entities in the PowerShell language including cmdlets, functions, scripts, and modules. A special emphasis is placed on the importance of the pipeline in PowerShell operations.

    Chapter 2, PowerShell Peculiarities, includes a number of features of the PowerShell language, which are unusual when compared with other mainstream programming languages. Examples of these topics are output from functions and non-terminating errors.

    Chapter 3, PowerShell Practices, shows a few ways that the scripting experience in PowerShell can be improved, either in performance or in maintainability. A lengthy discussion of the various output cmdlets is included.

    Chapter 4, PowerShell Professionalism, gives examples of practices that might not be as familiar to traditional system administrators but are common among professional developers. These practices will help scripters create more reliable products and be more confident when making changes to existing codebases.

    Chapter 5, Proactive PowerShell, presents a number of practices that, when applied to code, will result in more flexible code with fewer bugs. In a sense, this is pre-emptive troubleshooting, where we create our code thoughtfully in order to reduce the need for troubleshooting later.

    Chapter 6, Preparing the Scripting Environment, covers the idea of knowing the characteristics of the environment in which your scripts are running. We also spend some effort trying to weed out network connectivity issues.

    Chapter 7, Reactive Practices – Traditional Debugging, shows how to perform traditional troubleshooting in PowerShell using the debugging features of the console and the ISE, along with other techniques. It wraps up with an example of how using the wrong PowerShell feature to perform an operation can lead to poor performance.

    Chapter 8, PowerShell Code Smells, explains the concept of code smells (signs of poorly implemented code) and compares it with antipatterns, best practices, and technical debt. It then shows some ways that PowerShell code might begin to smell.

    What you need for this book

    Most of the examples in the book will work with PowerShell Version 2.0 and above. In places where a higher version of the engine is required, it will be indicated in the text. You should have no problems running the provided code on either a client installation (Windows 7 or greater) or a server installation (Windows Server 2008 R2 or greater).

    Who this book is for

    This book is intended for anyone who has some experience with PowerShell and would like to expand their understanding of the language design and features in order to spend less time troubleshooting their code. The examples are designed to be understood without needing any specific application knowledge (for example, Exchange, Active Directory, and IIS) in order to keep the intent clear. A few sections are aimed at system administrators specifically. This is due to the different skill set that most administrators bring to the table compared with developers. However, the points made are applicable to anyone using PowerShell.

    Conventions

    In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The Get-Help cmdlet has a number of switches that control precisely what help information is displayed.

    A block of code is set as follows:

    param($name)

        $PowerShellVersion=$PSVersionTable.PSVersion

        return We're using $PowerShellVersion, $name!

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    #find largest 5 items in the directory tree

    dir -recurse |

      tee-object –Variable Files |

     

      sort-object Length |

      tee-object –Variable SortedFiles |

     

      select-object -last 5

    Any command-line input or output is written as follows:

    Get-ChildItem c:\program files –include *.dll –recurse

    New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: It features a button labeled Scan Script, a gear button for options, and a grid for results.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

    To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via

    Enjoying the preview?
    Page 1 of 1