Statistics
5
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-18

AuthorMorten Elmstrøm Hansen

PowerShell is a powerful scripting language, automation framework and command-line shell developed by Microsoft that is built on the .NET framework. It is an essential tool because it allows system administrators and developers to automate and optimize complex administrative tasks across multiple systems efficiently. PowerShell's deep integration with Windows and other Microsoft products makes it an invaluable tool for administrating, managing and optimizing Windows environments. Designed as a cookbook, this book enables readers to expand and build upon their current PowerShell knowledge and skillset. Topics covered in detail include creating PowerShell unit tests using Pester, managing and administrating Azure and AWS cloud services, remote script execution, Active Directory management, PowerShell desired state configuration and more. Each chapter includes recipes that delves into the topics, accompanied by code examples and walkthroughs. After reading this book, readers...

Tags
No tags
ISBN: 9355516738
Publisher: BPB Publications
Publish Year: 2024
Language: 英文
File Format: PDF
File Size: 19.2 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
(This page has no text content)
PowerShell Advanced Cookbook Enhance your scripting skills and master PowerShell with 90+ advanced recipes Morten Elmstrøm Hansen
www.bpbonline.com
First Edition 2024 Copyright © BPB Publications, India ISBN: 978-93-55516-732 All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any form or by any means or stored in a database or retrieval system, without the prior written permission of the publisher with the exception to the program listings which may be entered, stored and executed in a computer system, but they can not be reproduced by the means of publication, photocopy, recording, or by any electronic and mechanical means. LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY The information contained in this book is true to correct and the best of author’s and publisher’s knowledge. The author has made every effort to ensure the accuracy of these publications, but publisher cannot be held responsible for any loss or damage arising from any information in this book. All trademarks referred to in the book are acknowledged as properties of their respective owners but BPB Publications cannot guarantee the accuracy of this information. www.bpbonline.com
Dedicated to My beloved wife Janni, my sons Theo- Maximillian and Milo-Matthæus, my family, my in-laws, my friends and my colleagues at Energi Danmark
About the Author Morten Elmstrøm Hansen is a dedicated IT professional and entrepreneur. For the past eight years he has been working at Energi Danmark, one of Denmark’s leading energy companies. He plays a central role in the IT operations department where he leverages his expertise in PowerShell development, DevOps and server administration to monitor, optimize and automate essential processes, ensuring operational continuity. Morten is proficient in containerization and kubernetes as well as cloud technologies and he utilizes his skills to be the forefront for larger projects involving such cutting-edge technologies. His professional qualifications include a certification in PowerShell Administration, an AP degree in IT technology and additional courses in digital marketing. Morten also holds a mix of several other technical and commercial educations such as a business college education that provides a solid foundation in commerce and administration, with a focus on economics, sales, communication and IT. Furthermore, he has a higher technical education that combines technical and scientific subjects with general academics. Additionally, he pursued a higher preparatory examination focusing on mathematics and psychology, further preparing him for his academic and professional pursuits in technology. In addition to his role in IT, Morten co-owns and serves as the part time CFO of a family cleaning business. He also owns and manages an online store, where he applies his
skills in digital marketing, IT and economics. His diverse roles demonstrate his ability to navigate and excel in multiple fields, from IT management and development to business operations. On a personal note, Morten is a devoted family man, living with his wife and two youngest children, on the outskirts of one of Denmark’s largest cities.
About the Reviewers ❖Lasse Hein Olesen is an IT Service Engineer, working within the MES and automation field, with an expertise in troubleshooting and problem solving. He is passionate about anything IT related and is always interested in learning something new and finding new challenges. He actually learned PowerShell from Morten, the author of this book. It is his first time being a technical reviewer. He’s currently focusing on advancing his PowerShell skills and expanding/building up his homelab. He is hoping to explore DevOps and Kubernetes in the near future. ❖Tibor Soós is a freelance PowerShell developer and trainer, having over 25 years of extensive experience in automating Windows, Active Directory, Exchange, Azure AD, Jira Service Desk and various Identity and Access Management systems like Saviynt, CyberArk, SecZetta. He has contributed his expertise to industry-leading enterprises, showcasing a deep understanding of PowerShell as a former MVP and the author of a Hungarian-language PowerShell book. Tibor is committed to empowering IT professionals with his wealth of knowledge and his enterprise-grade productivity modules, offering guidance and best practices to enhance their scripting and automation capabilities.
Acknowledgement My deepest gratitude and heartfelt appreciation to my wife Janni Elmstrøm Hansen and our two boys Theo-Maximillian and Milo-Matthæus. Without you and your continuous love and support, this book would never have become a reality. Even during moments of doubt and harsh times, you are always there to pick me up and make sure I follow my heart and my dreams. You will always be the love of my life and the soul of my being. I am also deeply grateful for the never-ending love and support from my family: My dad Johnny, my mom Lene, my brother Mads, and my sister Julie and for my wife´s family. Without you I would not be the person I am today. You have always picked me up, held me when needed and supported me, especially through the tough times in life. I would also like to thank and acknowledge all my close friends in life and all my colleagues at Energi Danmark. Thank you for your invaluable support and for always believing in me. You have all been instrumental in my personal and professional development throughout the years, and you have taught and given me more than I could have ever asked for. Additionally I would like to extend my sincerest appreciation to the reviewers of this book, Lasse Hein Olesen and Tibor Soós. Your input and attention to detail have been invaluable in creating this book and i am deeply grateful for your dedication and support.
Finally, I would like to thank BPB Publications for this incredible opportunity and for all the help and support throughout the journey of making this book become a reality.
Preface PowerShell is a powerful scripting language, automation framework and command-line shell developed by Microsoft that is built on the .NET framework. It is an essential tool because it allows system administrators and developers to automate and optimize complex administrative tasks across multiple systems efficiently. PowerShell's deep integration with Windows and other Microsoft products makes it an invaluable tool for administrating, managing and optimizing Windows environments. This book is intended for developers and system administrators with a novice or intermediate understanding of PowerShell who are looking to advance their skills. It is also beneficial for experienced professionals seeking to enhance their existing PowerShell capabilities. Designed as a cookbook, this book enables readers to expand and build upon their current PowerShell knowledge and skillset. Topics covered in detail include creating PowerShell unit tests using Pester, managing and administrating Azure and AWS cloud services, remote script execution, Active Directory management, PowerShell desired state configuration and more. Each chapter includes recipes that delves into the topics, accompanied by code examples and walkthroughs. After reading this book, readers should have gained knowledge and skills that enables them to build better and more advanced scripts and applications while also understanding key principles of automation and optimization. This will also enable the
readers to streamline processes and enhance administrative tasks more efficiently using PowerShell. Chapter 1: Introduction to Advanced PowerShell Concepts – Explores advanced PowerShell concepts, scripting best practices, and the configuration and setup of the Visual Studio Code Integrated Development Environment (IDE). The chapter also makes a short introduction to the different PowerShell versions available and furthermore, it introduces PowerShell providers which are used to facilitate and provide access to data across different data stores. Chapter 2: Advanced PowerShell Functions – Delves into advanced PowerShell functions and covers a detailed explanation of its structure and capabilities, including dynamic parameters, parameter sets and lifecycle events. It also covers key elements such as the CmdletBinding attribute, parameter validation and output formatting. Furthermore, it explains how to implement handling for pipeline input and the ShouldProcess capability. The chapter also introduces object-oriented PowerShell concepts in the form of PowerShell classes. It offers a step-by-step guide to constructing classes with properties and methods. Chapter 3: Flow Control and Looping – Is about using different methods for controlling and optimizing the flow of script execution. It introduces the reader to conditional statements using comparison and logical operators. It deeply covers advanced looping techniques such as nested loops, labelled breaks and continue statements, the use of retry logic in loops and the use of pipeline processing and also the Foreach-Object loop for iterating collections. Additionally, it explains how to utilize the switch statement to handle multiple conditions and it delves into using script blocks for dynamic and flexible flow control in terms of callbacks and event handlers. Furthermore, the chapter
introduces the reader to multi-threading in the forms of parallel processing using PowerShell jobs and non- sequential processing using the Foreach-Objects parallel parameter. Chapter 4: Error Handling – Dives deep into error handling in PowerShell and introduces the reader to topics such as handling different types of errors, implementing error handling blocks in advanced scenarios and how to use the ErrorAction preference variable and the ErrorAction parameter. It also showcase how to create custom error classes for enhanced error reporting and how to handle errors in background jobs. Chapter 5: Scripting Techniques – Focuses on a range of different scripting techniques that are common among different programming languages but with a focus on such techniques tailored specifically for PowerShell. The chapter covers topics such as script parameters, parameter validation, string manipulation and formatting techniques and scripting for cross-platform compatibility. Additionally, it introduces the reader to PowerShell execution policies and script signing for enhancing script security. Furthermore, the chapter dives deeper into the creation of PowerShell modules and repositories which are essential for organizing and distributing PowerShell code efficiently. Chapter 6: Remote Script Execution: PowerShell Remote Management – Guides the reader through setting up, configuring, and securely managing remote PowerShell sessions using PowerShell remoting and Windows remote management. It explains how to use session configurations to restrict and grant privileges and permissions for specific users and groups on remote hosts. The chapter also provides a more in-depth insight into securing and authenticating remote sessions using credentials, encrypted XML files, the Windows credential manager and also how to
configure secure and encrypted certificate-based authentication. Chapter 7: Testing with Pester – Introduces the reader to the Pester PowerShell testing framework. The chapter will guide the reader through setting up the Pester framework and it dives into Pesters structure and components. The chapter covers how to create unit tests for PowerShell functions, how to group and organize tests and how to mock dependencies. Furthermore, the chapter will provide strategies for testing infrastructure components and also how to implement code coverage analysis in tests. Chapter 8: Working with XML and JSON – Presents a detailed introduction to XML and JSON that are used for representing and structuring data in formats that are both human readable and easy for scripts and applications to interpret. While the main focus is targeted at XML, the reader will learn how to read and write XML files using cmdlets, the XML accelerator and by using .NET classes, but the reader will also learn how to read and write JSON files and how to convert between JSON and PowerShell objects. It also dives into querying and extracting data from XML files using XPath expressions and how to serialize and deserialize PowerShell objects using CliXml. Chapter 9: Active Directory Management - Delves into the essentials of managing and automating Active Directory tasks using PowerShell. This chapter introduces the ActiveDirectory module which is an essential tool in PowerShell for interacting with AD environments. The reader will learn how to manage AD users and groups efficiently. The chapter also introduces techniques for performing bulk operations, which are crucial in larger organizations where managing numerous accounts manually is impractical. Furthermore, it explores how to query and filter AD objects
effectively, using PowerShell's filtering capabilities to streamline administrative Active Directory tasks. Chapter 10: Managing Azure with PowerShell – Examens Azure cloud services management using the Azure command line interface (AzureCLI) and PowerShell. This chapter covers working with and managing Azure virtual machines, storage accounts, blobs, and file shares. It also dives deeper into Azure EntraID and focuses on the creation and management of users, groups, and resource access permissions. Additionally, it provides insight into automating resource provisioning and management focusing on creating service principals that are used for programmatically connecting to Azure using scripts and also how to create scripts that are used for configuration and automatic provisioning of Azure resources. Chapter 11: Managing AWS with PowerShell – Walks through AWS cloud services management and introduces the AWS tools for PowerShell. It describes how to install and configure these tools and also how to configure credentials for accessing AWS programmatically. The chapter dives deeper into AWS identity and access management (IAM) showcasing how to manage IAM users and groups and how to create and manage access keys, permissions, and policies. Furthermore, the chapter not only describes how to create and manage EC2 instances, key pairs and security groups but also how to manage S3 buckets and how to upload and download objects to such buckets. Chapter 12: Microsoft 365 Applications Management – Showcases how to install and use specific application modules that focus on different aspects of Microsoft 365 applications management. The chapter covers management of SharePoint online, Exchange online and Microsoft Teams using PowerShell. Additionally, it introduces the Microsoft Graph API and the Microsoft Graph PowerShell SDK module
describing installation, configuration, and authentication. Furthermore, the chapter gives an overview of how to manage Entra ID users and licenses using PowerShell and the modules. Chapter 13: Desired State Configuration – Provides an extensive insight into desired state configuration with PowerShell and outlines how to write and apply meta configurations from a centralized management server to remote nodes and DSC configurations on remote target nodes. This includes configuring local configuration managers, creating DSC configurations for managing infrastructure and using public resource modules. The chapter also describes how to remove resources and configurations and how to handle failed configurations. Chapter 14: Managing Windows Components – Is about using PowerShell to manage different Windows server and workstation components. The chapter covers how to create, manage, and delete windows services, how to start and manage processes, how to manage and configure network settings and how to initialize, partition and format disks. It also dives deeper into firewall rules and the Windows task scheduler. Chapter 15: SAPIEN PowerShell Studio IDE – Explores the advanced PowerShell IDE created by SAPIEN Technologies. This IDE takes PowerShell scripting to a new level and enables you to not only create advanced scripts from templates but also to easily create and compile sophisticated GUI applications, Windows services, and packaged executables from your PowerShell scripts. This chapter introduces the IDE and demonstrates how to use it to create GUI applications and Windows Services. Furthermore, it depicts how to compile scripts into executables and how to create MSI installers for executables using the packager and installer managers. It also peeks
into more applications created by SAPIEN Technologies such as the PowerShell module manager and the VersionRecall versioning and backup tool.
Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/q7m2itb The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/PowerShell- Advanced-Cookbook. In case there’s an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com
Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at : business@bpbonline.com for more details. At www.bpbonline.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 BPB books and eBooks. Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book’s Discord space Join the book’s Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors: