Enterprise PowerShell Scripting Bootcamp: The fastest way to learn PowerShell scripting
()
About this ebook
Enterprise PowerShell Scripting Bootcamp explains how to create your own repeatable PowerShell scripting framework. This framework contains script logging methodologies, answer file interactions, and string encryption and decryption strategies.
This book focuses on evaluating individual components to identify the system’s function, role, and unique characteristics. To do this, you will leverage built-in CMDlets and Windows Management Instrumentation (WMI) to explore Windows services, Windows processes, Windows features, scheduled tasks, and disk statistics. You will also create custom functions to perform a deep search for specific strings in files and evaluate installed software through executable properties.
We will then discuss different scripting techniques to improve the efficiency of scripts. By leveraging several small changes to your code, you can increase the execution performance by over 130%.
By the end of this book, you will be able to tie all of the concepts together in a PowerShell-based Windows server scanning script. This discovery script will be able to scan a Windows server to identify a multitude of components.
Read more from Brenton J.W. Blawat
Instant Windows Powershell 3.0 Windows Management Instrumentation Starter: Explore new abilities of Powershell 3.0 to interact with Windows Management Instrumentation (WMI) through the use of the new CIM cmdlets and realistic management scenarios. Rating: 0 out of 5 stars0 ratingsMastering Windows PowerShell Scripting - Second Edition: One-stop guide to automating administrative tasks Rating: 0 out of 5 stars0 ratings
Related to Enterprise PowerShell Scripting Bootcamp
Related ebooks
Enterprise PowerShell Scripting Bootcamp Rating: 0 out of 5 stars0 ratingsPowerShell Troubleshooting Guide Rating: 0 out of 5 stars0 ratingsSoftware Architect's Handbook: Become a successful software architect by implementing effective architecture concepts Rating: 0 out of 5 stars0 ratingsLearn PowerShell Core 6.0: Automate and control administrative tasks using DevOps principles Rating: 0 out of 5 stars0 ratingsMicrosoft System Center Orchestrator 2012 R2 Essentials Rating: 0 out of 5 stars0 ratingsCitrix XenApp Performance Essentials Rating: 0 out of 5 stars0 ratingsMicrosoft System Center Configuration Manager High availability and performance tuning Rating: 0 out of 5 stars0 ratingsMicrosoft Azure Security Rating: 0 out of 5 stars0 ratingsLearn Power BI: A beginner's guide to developing interactive business intelligence solutions using Microsoft Power BI Rating: 0 out of 5 stars0 ratingsLearning PowerShell DSC - Second Edition Rating: 0 out of 5 stars0 ratingsMastering Cloud Development using Microsoft Azure Rating: 0 out of 5 stars0 ratingsAzure Serverless Computing Cookbook Rating: 0 out of 5 stars0 ratingsLearning System Center App Controller Rating: 0 out of 5 stars0 ratingsHands-On Microservices with C#: Designing a real-world, enterprise-grade microservice ecosystem with the efficiency of C# 7 Rating: 0 out of 5 stars0 ratingsBuilding Bots with Microsoft Bot Framework Rating: 0 out of 5 stars0 ratingsImplementing Azure Solutions: Eliminate the pain point of implementation Rating: 0 out of 5 stars0 ratingsC# 7 and .NET Core 2.0 Blueprints: Build effective applications that meet modern software requirements Rating: 0 out of 5 stars0 ratingsINSTANT Windows PowerShell Rating: 0 out of 5 stars0 ratingsDeploying Microsoft System Center Configuration Manager Rating: 0 out of 5 stars0 ratingsMastering Windows Presentation Foundation: Build responsive UIs for desktop applications with WPF, 2nd Edition Rating: 0 out of 5 stars0 ratingsOracle JET for Developers: Implement client-side JavaScript efficiently for enterprise Oracle applications Rating: 0 out of 5 stars0 ratingsLearning Azure DocumentDB Rating: 0 out of 5 stars0 ratingsWindows 10 for Enterprise Administrators: Modern Administrators' guide based on Redstone 3 version Rating: 0 out of 5 stars0 ratingsDrupal Search Engine Optimization Rating: 0 out of 5 stars0 ratingsTeam Foundation Server 2015 Customization Rating: 0 out of 5 stars0 ratingsEnterprise Application Architecture with .NET Core: An architectural journey into the Microsoft .NET open source platform Rating: 0 out of 5 stars0 ratings
System Administration For You
Cybersecurity: The Beginner's Guide: A comprehensive guide to getting started in cybersecurity Rating: 5 out of 5 stars5/5Learn SQL Server Administration in a Month of Lunches Rating: 3 out of 5 stars3/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5CompTIA A+ Complete Review Guide: Core 1 Exam 220-1101 and Core 2 Exam 220-1102 Rating: 5 out of 5 stars5/5Linux Command-Line Tips & Tricks Rating: 0 out of 5 stars0 ratingsLinux Bible Rating: 0 out of 5 stars0 ratingsNetworking for System Administrators: IT Mastery, #5 Rating: 5 out of 5 stars5/5The Complete Powershell Training for Beginners Rating: 0 out of 5 stars0 ratingsImprove your skills with Google Sheets: Professional training Rating: 0 out of 5 stars0 ratingsMastering Windows PowerShell Scripting Rating: 4 out of 5 stars4/5Wordpress 2023 A Beginners Guide : Design Your Own Website With WordPress 2023 Rating: 0 out of 5 stars0 ratingsLinux Commands By Example Rating: 5 out of 5 stars5/5RHCSA Exam Pass: Red Hat Certified System Administrator Study Guide Rating: 0 out of 5 stars0 ratingsGit Essentials Rating: 4 out of 5 stars4/5Bash Command Line Pro Tips Rating: 5 out of 5 stars5/5Learn PowerShell Scripting in a Month of Lunches Rating: 0 out of 5 stars0 ratingsBuilding a Plex Server with Raspberry Pi Rating: 0 out of 5 stars0 ratingsPractical Data Analysis Rating: 4 out of 5 stars4/5Mastering Linux Shell Scripting Rating: 4 out of 5 stars4/5Learning Microsoft Endpoint Manager: Unified Endpoint Management with Intune and the Enterprise Mobility + Security Suite Rating: 0 out of 5 stars0 ratingsMastering Bash Rating: 5 out of 5 stars5/5Windows 11 Manual For Seniors: A Beginners Guide to Navigate Your Computer with Step-by-Step Instructions Rating: 3 out of 5 stars3/5PowerShell: A Comprehensive Guide to Windows PowerShell Rating: 4 out of 5 stars4/5Learn Windows PowerShell in a Month of Lunches Rating: 0 out of 5 stars0 ratingsWindows Security Basics: User Accounts Rating: 0 out of 5 stars0 ratingsLearning ServiceNow Rating: 5 out of 5 stars5/5
Reviews for Enterprise PowerShell Scripting Bootcamp
0 ratings0 reviews
Book preview
Enterprise PowerShell Scripting Bootcamp - Brenton J.W. Blawat
Table of Contents
Enterprise PowerShell Scripting Bootcamp
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Customer Feedback
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
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with Enterprise PowerShell Scripting
Windows server scanning script
Performance considerations
PowerShell scripting templates
Summary
2. Script Structure, Comment Blocks, and Script Logging
Overall script structure
Comment blocks
Script logging
Creating the logging files
Creating a windows event log source
Creating the logging function
Summary
3. Working with Answer Files
Answer files
XML answer files
Reading XML answer files
XML tag function
Summary
4. String Encryption and Decryption
RijndaelManaged encryption
Creating random salt, initialization vector, and passwords
Encrypting and decrypting strings
Decrypting strings
Securing the password
Decryption with encoded password
Summary
5. Interacting with Services, Processes, Profiles, and Logged on Users
Windows services
Managing Windows processes
Identifying logged on users
User profiles
Summary
6. Evaluating Scheduled Tasks
Scheduled tasks
Identifying scheduled tasks running as alternate users
Summary
7. Determining Disk Statistics
Disk statistics
Retrieving physical and logical disk information
The DriveType property
Converting disk space to MB and GB
Free Space property
Disk information script
Summary
8. Windows Features and Installed Software Detection
Windows features
Installed software detection
Scanning executables in \Program Files
Summary
9. File Scanning
File scanning
Excluding long paths
Excluding files
Summary
10. Optimizing Script Execution Speed
Script execution speed
Speed considerations for the write-host cmdlet
Speed considerations for the write-progress cmdlet
Speed consideration - switches versus if statements
Summary
11. Improving Performance by Using Regular Expressions
Using regular expressions
Dynamically building expressions
Implementating regular expression performance
Summary
12. Overall Script Workflow, Termination Files, and Merging Data Results
Windows server scanning script overview
Pre-script security
Script 1 - randomized password and string generator
Script 2 - string encryption script
XML answer file creation
PowerShell script 3 - the termination files
PowerShell script 4 - merging the scanning script result data
Summary
13. Creating the Windows Server Scanning Script and Post-Execution Cleanup
Windows server scanning script creation
Comment block
Parameter block
Answer file reading function
Decryption function
Populating script answers in variables and arrays
Creating the log files and logging function
Creating a termination function
Multiple Windows server scanning script functions
Scheduled tasks function
Windows processes function
Windows services function
Installed software function
User profiles function
Windows features function
Scan files and folders function
Invoking the functions
Running the script
Performing script cleanup
Summary
Index
Enterprise PowerShell Scripting Bootcamp
Enterprise PowerShell Scripting Bootcamp
Copyright © 2017Packt 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: May2017
Production reference: 1160517
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B32PB, UK.
ISBN 978-1-78728-828-7
www.packtpub.com
Credits
Author
Brenton J.W. Blawat
Reviewer
Tim Amico
Commissioning Editor
Kartikey Pandey
Acquisition Editor
Namrata Patil
Content Development Editor
Amrita Noronha
Technical Editor
Jovita Alva
Copy Editors
Safis Editing
Laxmi Subramanian
Project Coordinator
Shweta H Birwatkar
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Graphics
Tania Dutta
Production Coordinator
Nilesh Mohite
Cover Work
Nilesh Mohite
About the Author
Brenton J.W. Blawat is an entrepreneur, strategic technical advisor, multi-published author, and enterprise architect who has a passion for the procurement of technology in profit-based organizations. Brenton is business-centric, while technology minded, and has many years of experience bridging the gap between technical staff and decision makers in organizations. He takes pride in his ability to effectively communicate to a diverse audience and provide strategic direction for large and small organizations alike.
Since 2013, he has authored and published multiple books with Packt Publishing, including:
PowerShell 3.0 WMI Starter
(Co-authored) PowerShell: Automating Administrative Tasks
Mastering Windows PowerShell Scripting
Brenton currently works at CDW as an enterprise architect in Strategic Solutions and Services. CDW is a leading multibrand technology solutions provider to business, government, education, and healthcare organizations in the United States, Canada, and the United Kingdom. A Fortune 500 company with multinational capabilities, CDW was founded in 1984 and employs approximately 8,500 workers. For the year ending December 31, 2016, the company generated net sales of nearly $14 billion. For more information about CDW, visit www.CDW.com.
As the author of this book, Brenton always extends himself to the PowerShell community. You can follow Brenton on Twitter at @brentblawat or his blog at http://www.masteringposh.com. The author is always open for discussions on the book and will provide feedback to readers, as time allows. If you are an academic institution, Brenton engages with multiple colleges for guest speaking. You can contact Brenton on Twitter for more information.
Happy coding!
About the Reviewer
Tim Amico is a passionate technology leader with years of consulting experience around designing, implementing, and managing Endpoint and Mobility management infrastructures for small organizations to large global enterprise environments. He has continued to define technology solutions that help solve complex business problems and deliver highly customized solutions to clients.
He currently works at LMI as a systems engineer, managing their System Center Configuration Manager, Active Directory, and Azure IaaS environments. LMI is a not-for-profit government consulting firm that designs and implements solutions to some of the toughest problems facing government managers in logistics, information technology, and resource allocation. For more information about LMI, visit www.lmi.org.
You can follow Tim on twitter at @tim_amico or his blog at http://www.deploymentlife.com.
www.PacktPub.com
eBooks, discount offers, and more
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
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.
eBooks, discount offers, and morehttps://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
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
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787288285.
If you'd like to join our team of regular reviewers, you can e-mail us at <[email protected]>. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
I would like to dedicate this book to my wife, Rachel, whose love and support drives me to be a better person every day.
Preface
PowerShell is quickly becoming the language of choice to support Microsoft systems in organizations. With Microsoft's deep integration of PowerShell in all of their software and cloud services, scripting knowledge will be a required skill set in the years to come. Even third-party vendors are creating modules or plugins to extend the PowerShell manageability of their systems. As a result, organizations are relying on their cross-platform engineers to automate systems through the use of PowerShell.
When you are implementing PowerShell scripts in enterprise environments, there are many common challenges that need to be solved. Robust logging functions, for example, are typically required to ensure that the script ran successfully and as intended. You may also need to implement a string encryption strategy to encrypt credentials, server host names, IP addresses, or other sensitive data. Further more, script execution speed may also take some consideration when processing large sets of data. You will want to ensure you are leveraging the fastest coding methods possible to optimize your scripting performance.
All of these challenges, and many more, can be solved by leveraging PowerShell. Through both native cmdlets and the .NET Framework, you can create sophisticated scripts to solve almost any problem. The PowerShell community of developers is very passionate about sharing their knowledge and providing information on how to solve problems. Through code sharing websites, social media, and Microsoft's TechNet, there is always a constant stream of examples that you can implement in your code. Also, now that PowerShell is open source and available on Linux, it deepens the relationships with the open source community. It provides a much wider set of open source developers to solve enterprise problems.
This book has been designed to teach you the ins and outs of enterprise PowerShell scripting. It is geared towards real-world scenarios of how Fortune 500 companies leverage PowerShell to solve problems. It provides a scripting framework that you can easily follow to start integrating the examples into your own scripts. At the end of this book, you will have learned many techniques to secure, optimize, and deliver PowerShell scripts that are ready to be deployed in the enterprise.
What this book covers
Chapter 1, Getting Started with Enterprise PowerShell Scripting, introduces the Windows server scanning script and performance considerations, and helps you create your own PowerShell scripting templates.
Chapter 2, Script Structure, Comment Blocks, and Script Logging, explores how to structure your PowerShell scripts, how to properly comment your script, and how to create a robust logging function.
Chapter 3, Working with Answer Files, explains the purpose of XML-based answer files and displays how to leverage them in your scripts.
Chapter 4, String Encryption and Decryption, dives into advanced string encryption and encoding methodologies. It shows you how to securely store encrypted data in scripts, and a how to decrypt and decode values during runtime.
Chapter 5, Interacting with Services, Processes, Profiles, and Logged-on Users, evaluates different Windows server components for nonstandard configurations. It also evaluates logged-on users and user profiles to identify what users have been interacting with a particular system.
Chapter 6, Evaluating Scheduled Tasks, displays how to interact with scheduled tasks on a system. It helps identify the different processes that may be invoked on a scheduled basis on a system.
Chapter 7, Determining Disk Statistics, explores how to interact with the disks on a system to retrieve and record disk information.
Chapter 8, Windows Features and Installed Software Detection, explains how to review the installed Windows features and installed software on a system.
Chapter 9, File Scanning, dives into scanning for file types in directories on a server. It also displays the process to scan for strings in files.
Chapter 10, Optimizing Script Execution Speed, evaluates how to increase server performance through the use of different scripting techniques. It also evaluates how to measure command execution time for benchmarking script performance.
Chapter 11, Improving Performance Using Regular Expressions, displays how to leverage regular expressions to significantly increase the performance of your PowerShell scripts.
Chapter 12, Overall Script Workflow, Termination Files, and Merging Data Results, evaluates the overall Windows server scanning script workflow and the full answer file creation. It also explores when and why you would use termination files and how to merge the results from the Windows server scanning script.
Chapter 13, Creating the Windows Server Scanning Script and Post Execution Cleanup, provides an in-depth explanation of all of the components in the Windows server scanning script. It also provides cleanup considerations for postscript execution on systems.
What you need for this book
To work through the examples provided in Enterprise PowerShell Scripting Bootcamp, you will need access to two Server 2012 R2, or greater, Windows Server operating systems. Preferably, both systems will be joined to a domain. The chapters in this book highly rely on Windows Management Framework and it is recommended to leverage version 5.0 for PowerShell 5.0. You will need to download and install Windows Management Framework on the systems you are running these examples on.
Who this book is for
Enterprise PowerShell Scripting Bootcamp has been designed for PowerShell scripters that are both beginner- and advanced-level coders. After reading this book, you will have in-depth knowledge of PowerShell scripting in enterprises and will create a working script to execute in your environment. Previous scripting and basic coding experience is required to understand the concepts presented in this book.
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-service cmdlet is used to retrieve detailed information about Windows Services.
A block of code is set as follows:
$sid = S-1-5-18
$usersid = New-Object System.Security.Principal.SecurityIdentifier($SID
) $usersid.Translate( [System.Security.Principal.NTAccount]).Value
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: clicking the Next button moves you to the next screen
.
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 <[email protected]>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Enterprise-PowerShell-Scripting-Bootcamp. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/EnterprisePowerShellScriptingBootcamp_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <[email protected]> if you are having a problem with any aspect of