Learn windows powershell in a month of lunches

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team — learn more


new edition available

this edition is free when you purchase

Learn PowerShell in a Month of Lunches, Fourth Edition

Look inside

Learn Windows PowerShell in a Month of Lunches, Third Edition is an innovative tutorial designed for busy IT professionals. This updated edition covers PowerShell features that run on Windows 7, Windows Server 2008 R2 and later, PowerShell v3 and later, and includes v5 features like PowerShellGet.

about the technology

PowerShell is both a scripting language and an administrative shell that lets you control and automate nearly every aspect of Windows. It accepts and executes commands interactively and you can write scripts to manage most Windows servers like Exchange, IIS, and SharePoint, as well as online services like Azure and Office 365.

about the book

Learn Windows PowerShell in a Month of Lunches, Third Edition is an innovative tutorial designed for busy IT professionals. Just set aside one hour a day — lunchtime would be perfect — for a month, and you’ll be automating Windows tasks faster than you ever thought possible. This updated edition covers PowerShell features that run on Windows 7, Windows Server 2008 R2 and later, PowerShell v3 and later, and includes v5 features like PowerShellGet.

what’s inside

  • Learn PowerShell from the beginning, no experience required!
  • Covers PowerShell v3 and up, Windows 7, and Windows Server 2008 R2 and later
  • Each lesson takes you an hour or less

about the reader

Experience with Windows administration is helpful. No programming or scripting experience needed.

about the authors

Veteran PowerShell MVPs Don Jones and Jeffery Hicks bring years as successful trainers to this concise, easy-to-follow book.

Superb…full of real-world examples, this book is an IT specialist’s best friend.

Your key to learning Windows PowerShell.

A must-have…both novice and expert will benefit from this book.

Learn PowerShell fundamentals from the experts.

choose your plan

pro

$249.99

only $20.83 per month


  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • Learn Windows PowerShell in a Month of Lunches, Third Edition ebook for free

team

$399.99

only $33.33 per month


  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • Learn Windows PowerShell in a Month of Lunches, Third Edition ebook for free

5.0 out of 5 stars

If only all my previous books had been presented like this one.

I’ve always been known as a bit of a scripter in work, but it’s mainly been the odd for loop from the command line and learning all the command line inputs for lots of different products etc. (csvde, ldife, psexec, putty, adsi etc.) With these skills it’s been a bit like the adage about sausages and laws. (You don’t want to know how they’re made, just enjoy the end results.) A lot of what I’ve done has been from the culmination of running say a few batch files one after the other but getting there in the end. I guess what I’m trying to say is I was a frustrated scripter.

I’ve counted up all the books I’ve bought whereby I’ve ‘tried’ to teach myself scripting methods, vbscript, perl, wmi, etc however I kind of glazed over, gave up the ghost or just went back to doing it the ‘old faithful’ way as I didn’t have time to keep working through the learning curve. Like most of us, I’m busy enough in work keeping all the plates spinning that the last thing I needed to do was put up another plate!

Anyway, I’ve also ‘played’ with powershell quite a bit, starting back when it first came out and the snapins for VMWare came back in version 1.0. I got so much out of reporting on the Virtual Center etc that I’m told they still use a lot of the scripts I originally wrote. (And like most other people out there I guess, a lot of what I wrote came from stuff I’d found online that was excellent and freely available.) It got to the stage where I was just holding myself back with powershell so I looked around and actually bought a few other books but they joined the pile of other books gathering dust (I’ve counted them and I’ve spent over £150 on them since 2003!), I saw the good reviews on here, googled the author started following him on twitter and eventually bought the book.

Boy do I wish I’d bought it as soon as it came out. Instantly I was eager to get to the next chapter and learn more, he gets you to do things sometimes in a roundabout way that helps you understand why and what’s even better is there are videos freely available from the <…> website that really nail the chapters.

In the end I of course encountered some difficulties (the problem has always been between the keyboard and the chair! ;o) and I remembered reading that the author was available on the forums so I posted my question and it was answered almost immediately. It was like actually being in a classroom. What’s more, it’s eminently he’s got the skills to back up his teaching which is something I usually find find lacking in ‘trainers’ that merely present powerpoint slides. He knew almost to a keystroke what I had done wrong and put me back on the right path. I’ve since gone on to nearly finishing the book (I’m on Chapter 21), I was going to wait until I had but not reviewing how good this is isn’t fair on anyone else that’s thinking about developing or learning powershell skills. Plus, it’s like Don Jones says, you can either learn Powershell or learn to ask ‘Would you like fries with that?’ :o)

A few top tips I’ve learnt is take your time and study the errors when they occur (and they will), don’t be embarrassed at mistakes, we all make them and there’s a whole community of people out there who are just as passionate about this tool who are more than willing to help out. In the end, it doesn’t matter how it’s done, it matters that it gets done. It’ll start looking ‘nicer’ the more that you do and I intend on doing it a lot from now on. If you do it more than once, script it!

Seriously, the concepts and methods this book teaches you in just a few weeks will have your knowledge up to intermediate if not advance.

Finally, as has been mentioned on here, you get access to the ebook with this book as well. Details are in the book. This is certainly a book for reading from cover to cover, not one for jumping in perusing an individual chapter, although you could do that if you needed to. One of the best things I like is that there is a ‘new’ version of this book coming out to support powershell 3 (It’s coming with Windows 8 and Server 2012, but to be honest that’s not going to be in ‘production’ environments for quite some time so I recommend this book if your a busy admin like me.) I caught a tweet from author about this new book and asked him what he suggested I do. Instead of trying to cream me to buy this ‘new improved’ book he told me to wait until his advanced book about «PowerShell Scripting and Toolmaking in a Month of Lunches» comes out as that would be a natural progression for me. Where do you get that kind of counsel these days?

As if you couldn’t tell, I’m sold, both on the authors method of delivery but also on the book range.

1. PowerShell is a Command-Line Shell, Not Just a Scripting Language

I realized that PowerShell isn’t really a scripting language. It’s really a command-line shell where you run command-line utilities.

Shell First. PowerShell is fundamentally a command-line shell, similar to Cmd.exe or Unix shells. Its primary function is to execute commands and utilities, making it an interactive tool for system administration. While it possesses scripting capabilities, these are secondary to its core function as a shell.

Command-Centric Approach. The initial focus should be on running individual commands and understanding their parameters. This approach allows users to quickly achieve practical results without immediately delving into complex scripting concepts. Many familiar commands from Cmd.exe, such as dir, cd, copy, and del, are available as aliases in PowerShell, easing the transition for users accustomed to the traditional command-line interface.

Gradual Scripting. As users become more comfortable with running commands, they can gradually transition to scripting by combining commands into reusable sequences. This approach allows users to build upon their existing knowledge and skills, making the learning process more manageable and effective. PowerShell’s ability to run external command-line utilities alongside native cmdlets provides a bridge for administrators familiar with traditional tools.

2. Mastering the Help System is Key to PowerShell Proficiency

If you aren’t willing to read PowerShell’s help files, you won’t be effective with PowerShell.

Discoverability. PowerShell’s help system is a crucial tool for discovering commands and understanding their usage. It provides detailed information on cmdlet syntax, parameters, and examples, enabling users to effectively utilize the shell’s capabilities. The Get-Help cmdlet is the primary means of accessing the help system.

Comprehensive Information. The help system includes not only cmdlet-specific information but also background topics and conceptual overviews. These «about» topics provide valuable context and understanding of PowerShell’s underlying principles. The -online parameter of Get-Help provides access to the most up-to-date help content on Microsoft’s TechNet website.

Practical Application. The help system is essential for troubleshooting errors and understanding how to connect commands in a pipeline. By mastering the help system, users can effectively learn and use PowerShell in a production environment. The Help function pipes the output to More so that you get a nice paged view instead of seeing all the help fly by at once.

3. The Pipeline Enables Powerful Command Combinations

The pipeline is simply a way for one command to pass, or pipe, its output to another command, so that the second command has something to work with.

Connecting Commands. The pipeline is a fundamental concept in PowerShell, allowing users to connect multiple commands together to perform complex tasks. The output of one command is passed as input to the next, creating a seamless flow of data. The | symbol is used to create a pipeline.

Data Transformation. The pipeline enables users to transform data from one format to another. For example, the output of Get-Process can be piped to Export-Csv to save the process information to a CSV file. The Export-CliXML cmdlet creates a generic command-line interface (CLI) Extensible Markup Language (XML) file.

Efficient Workflow. The pipeline reduces the need for intermediate steps and temporary files. By connecting commands directly, users can streamline their workflow and achieve results with less typing. The Diff cmdlet is designed to take two sets of information and compare them to each other.

4. Extending PowerShell with Modules and Snap-ins

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Extensibility. PowerShell’s extensibility allows it to manage a wide range of technologies and products. Modules and snap-ins provide a means of adding new commands and functionality to the shell. Installing the management tools for products like Exchange Server, SharePoint Server, and SQL Server typically adds PowerShell extensions.

Modules vs. Snap-ins. Modules are designed to be more self-contained and easier to distribute than snap-ins. Modules don’t require advanced registration. Snap-ins (PSSnapins) were first created for PowerShell v1.

Discovering and Adding Extensions. The Get-Module -ListAvailable cmdlet lists available modules, while Add-Module loads a specific module. The Get-PSSnapin -Registered cmdlet lists registered snap-ins, and Add-PSSnapin loads a snap-in. The Get-Command cmdlet can be used to discover the commands added by a module or snap-in.

5. Objects: The Foundation of PowerShell Data Handling

The truth is that PowerShell doesn’t actually contain a Dir command, or a Type command, or any of those other commands. Instead, PowerShell defines those as aliases to some of PowerShell’s native cmdlets.

Object-Oriented Approach. PowerShell treats all data as objects, which have properties (attributes) and methods (actions). This object-oriented approach enables users to manipulate data in a structured and consistent manner. The Get-Member cmdlet (alias Gm) is used to discover the properties and methods of an object.

Properties and Methods. Properties contain information about an object, such as its name, size, or status. Methods are actions that can be performed on an object, such as starting, stopping, or deleting it. The Sort-Object cmdlet sorts objects based on their properties.

Collections. A collection is a set of objects. PowerShell’s pipeline passes collections of objects from one command to another. The Select-Object cmdlet selects specific properties from a collection of objects.

6. Remote Control: PowerShell’s Reach Across Networks

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Remote Management. PowerShell’s remoting capabilities enable users to manage remote computers from a central location. This feature is essential for automating tasks across a network. PowerShell uses the Windows Remote Management (WinRM) service, which is based on the Web Services for Management (WS-MAN) protocol.

One-to-One and One-to-Many Remoting. PowerShell supports two types of remoting: one-to-one (1:1) and one-to-many (1:n). One-to-one remoting involves establishing an interactive session with a single remote computer, while one-to-many remoting involves sending commands to multiple remote computers simultaneously. The Enter-PSSession and Exit-PSSession cmdlets are used for 1:1 remoting.

Invoke-Command. The Invoke-Command cmdlet is used for 1:n remoting. It allows users to execute commands on multiple remote computers in parallel. The -ComputerName parameter specifies the target computers, and the -ScriptBlock parameter specifies the commands to be executed.

7. WMI: Accessing a Wealth of System Information

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Centralized Management. Windows Management Instrumentation (WMI) provides a standardized way to access management information about Windows systems. It allows users to query system hardware, software, and configuration settings. WMI is organized into namespaces, classes, and instances.

WMI Providers. WMI relies on providers, which are components that expose management information for specific technologies. For example, the DNS Server role installs a WMI provider that allows users to query DNS records. The Get-WmiObject cmdlet is used to query WMI.

WMI Explorer. The WMI Explorer tool can be used to browse the WMI repository and discover available classes and properties. The -filter parameter of Get-WmiObject allows users to specify criteria for retrieving specific instances.

8. Background Jobs: Multitasking in PowerShell

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Asynchronous Execution. PowerShell’s background jobs feature enables users to run commands asynchronously, allowing them to continue working in the shell while the commands execute in the background. This is particularly useful for long-running tasks. The Start-Job cmdlet creates a local job.

Job Management. PowerShell provides several cmdlets for managing background jobs, including Get-Job, Receive-Job, Stop-Job, and Remove-Job. The Get-Job cmdlet lists available jobs and their status. The Receive-Job cmdlet retrieves the results of a job.

WMI and Remoting as Jobs. The -AsJob parameter can be added to Get-WmiObject and Invoke-Command to run those commands as background jobs. This allows users to perform WMI queries and remote administration tasks without blocking the shell.

9. Automating Mass Management: Efficiently Handling Multiple Objects

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Batch Cmdlets. Many PowerShell cmdlets are designed to accept batches of objects as input, allowing users to perform actions on multiple items simultaneously. This approach is more efficient than enumerating objects one at a time. The Stop-Service, Start-Service, Move-ADObject, and Move-Mailbox cmdlets are examples of batch cmdlets.

WMI Methods. WMI methods can be used to perform actions on multiple objects. The Invoke-WmiMethod cmdlet is used to execute methods on WMI objects. The ForEach-Object cmdlet can be used to enumerate objects and execute methods on each one.

Object Enumeration. The ForEach-Object cmdlet can be used to enumerate objects and perform actions on each one. This approach is useful when there is no batch cmdlet available or when you need to perform custom actions on each object.

10. Security First: Protecting Your PowerShell Environment

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Execution Policy. PowerShell’s execution policy is a security feature that controls the scripts that can be executed. The default setting, Restricted, prevents scripts from being executed at all. The Get-ExecutionPolicy cmdlet displays the current execution policy.

Code Signing. Digital code signing is the process of applying a cryptographic signature to a script. This signature verifies the identity of the script author and ensures that the script has not been modified. The Set-AuthenticodeSignature cmdlet is used to sign scripts.

Security Recommendations. Microsoft recommends using the RemoteSigned execution policy, but a more secure approach is to use AllSigned and sign all scripts with a code-signing certificate. The .PS1 filename extension is not considered an executable file type by Windows, and the shell does not search the current directory for scripts.

11. Variables: Storing and Manipulating Data

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Storing Values. Variables are used to store data in PowerShell. Variable names start with a dollar sign ($). The assignment operator (=) is used to assign a value to a variable.

Data Types. PowerShell automatically determines the data type of a variable based on the value assigned to it. However, you can explicitly declare a variable’s type using square brackets (e.g., [int]$number = 100). The Get-Member cmdlet (alias Gm) is used to discover the properties and methods of a variable.

String Manipulation. String objects have a variety of methods for manipulating text, including IndexOf(), Split(), Join(), Replace(), ToLower(), and ToUpper(). The -join and -split operators are designed to convert arrays to delimited lists and vice versa.

12. Scripting Essentials: Logic, Loops, and Functions

The goal behind Windows PowerShell is that Microsoft builds 100 percent of a product’s administrative functionality in the shell.

Conditional Logic. The If construct is used to execute commands based on a condition. The ElseIf and Else keywords can be used to create more complex conditional logic. The Switch construct is used to compare a value against multiple possible values.

Loops. The For construct is used to repeat a block of commands a specific number of times. The ForEach construct is used to enumerate a collection of objects and execute a block of commands for each object.

Functions. Functions are reusable blocks of code that can be called by name. Functions can accept parameters and return values. The Param() block is used to define parameters for a function.

Last updated:

Discover a streamlined approach to mastering Windows PowerShell with «Learn Windows PowerShell in a Month of Lunches» by Don Jones. This engaging tutorial is tailored for busy administrators who need to efficiently manage and automate Windows systems. With thousands of controls and settings scattered across various interfaces, PowerShell offers a powerful, unified command line to simplify administration tasks. In just one hour a day over the course of a month—perfect for your lunch break—you’ll gain the skills to expedite your workflows and enhance your productivity. The book includes access to a complimentary PDF, ePub, and Kindle eBook, along with all the code featured in the text to support your learning journey.

Don Jones is a prolific author with numerous books and eBooks on information technology, best recognized for his acclaimed «Month of Lunches» series published by Manning. Recently, he has expanded his writing repertoire to include business management, instructional design, and self-improvement, as well as delving into the realms of science fiction and fantasy. Residing in Downtown Las Vegas, Nevada, Don is an avid enthusiast of Disney Parks, with a particular fondness for Figment.

Chapter 1 | Before you begin

Chapter 1: Before You Begin

1.1. Why You Can’t Afford to Ignore PowerShell
The transition from previous scripting languages like VBScript to PowerShell marks a significant development for Windows administrators. PowerShell is designed not just for scripting but as a command-line shell to run utilities efficiently. Its growing popularity is due to the need for enhanced administration capabilities.

1.1.1. Life Without PowerShell
Before PowerShell, administrators relied on GUIs for task execution, resulting in inefficiency. While scripting languages like VBScript improved productivity for certain tasks, they fell short due to inconsistent support from Microsoft.

1.1.2. Life with PowerShell
PowerShell enables full access to a product’s administrative functions, allowing automation of repetitive tasks. This integration signifies a shift in administration practices, promoting efficiency and command-line operations.

1.2. And Now, It’s Just “PowerShell”
In 2016, Microsoft open-sourced PowerShell, extending its availability to macOS and Linux, thereby fostering a broader community for its evolution.

1.3. Is This Book for You?
The book targets three PowerShell user categories: command executors, process combiners, and tool developers, focusing primarily on new users to enhance command-line skills and automation understanding.

1.4. How to Use This Book
Designed for a daily reading routine, the book comprises main chapters, hands-on labs, and supplementary materials for effective learning and practice, encouraging exploration beyond initial content.

1.5. Setting Up Your Lab Environment
Users need a lab environment with PowerShell v3 or later for practice. Recommendations include using Windows 8.1 or later on a 64-bit system and avoiding production environments for practice.

1.6. Installing Windows PowerShell
PowerShell v3 is preinstalled on newer Windows versions, and users should check and install the appropriate version to ensure compatibility with book content.

1.7. Contacting Us
Feedback is encouraged through social media and forums for support and additional resources related to PowerShell.

1.8. Being Immediately Effective with PowerShell
The book emphasizes practical application over extensive theory, aiming to make users effective immediately by focusing on real-world tasks and gradually introducing nuanced details.

Chapter 2 | Meet PowerShell

Chapter 2: Meet PowerShell

This chapter introduces PowerShell and guides users on choosing the appropriate interface for Windows PowerShell.

2.1. Choose Your Weapon

Microsoft offers multiple ways to access PowerShell on Windows, including four main icons depending on whether the system is 32-bit or 64-bit. Users are encouraged to use the 64-bit versions for better compatibility with extensions.

2.1.1. The Console Window

The PowerShell console window is the most standard way to interact with PowerShell. Though it has limitations, such as inconsistent character support and non-standard keystrokes for clipboard operations, it can be essential for server environments without a GUI. There are tips for configuring the console for better usability, including increasing the font size, adjusting the command history buffer, and setting a high-contrast color scheme.

2.1.2. The Integrated Scripting Environment (ISE)

The PowerShell ISE provides a more user-friendly interface, supporting features like double-byte character sets and traditional copy-paste operations. Key areas include the Script Editor, Console pane, and Command Explorer. Configuration options are available to customize user experience through color schemes and layouts.

2.2. It’s Typing Class All Over Again

Effective typing is crucial in PowerShell, and both the console and ISE offer features to minimize typing errors, such as Tab completion and IntelliSense in the ISE. Accuracy in command typing is emphasized to avoid common errors.

2.3. Common Points of Confusion

Several common issues may trip users up, including configuring the console to avoid horizontal scrollbars, understanding the importance of using the correct 32-bit versus 64-bit applications, and ensuring the application window is running with administrative privileges.

2.4. What Version Is This?

It’s important to verify the PowerShell version in use. Users can check their version with the `$PSVersionTable` command. Users are urged to ensure they are running at least version 3.0.

2.5. Lab

This lab aims to set up the console and ISE according to user preferences. Users should adjust fonts and colors, eliminate horizontal scrollbars in the console, maximize the console pane in ISE, and ensure characters like quotes and brackets are distinguishable. These steps reinforce the learning objectives of setting up a user-friendly environment in PowerShell.

Section Description
Chapter 2: Meet PowerShell Introduces PowerShell and helps users choose the appropriate interface.
2.1. Choose Your Weapon Discusses multiple ways to access PowerShell with an emphasis on 64-bit versions.
2.1.1. The Console Window Describes the standard console method, its limitations, and usability tips.
2.1.2. The Integrated Scripting Environment (ISE) Explains the user-friendly interface of ISE with customization options.
2.2. It’s Typing Class All Over Again Emphasizes effective typing and tools like Tab completion and IntelliSense.
2.3. Common Points of Confusion Discusses common issues like console configuration and application privileges.
2.4. What Version Is This? Instructs users on checking their PowerShell version and suggests using version 3.0 or higher.
2.5. Lab Provides practical steps to set up the console and ISE for a user-friendly experience.

Chapter 3 | Using the help system

Chapter 3: Using the Help System

Overview
This chapter emphasizes the importance of the PowerShell help system in enhancing discoverability and effectiveness for users, distinguishing it from graphical user interfaces (GUIs). Familiarization with the help system is essential for proficiency in PowerShell.

3.1. The Help System: Discovering Commands
— The PowerShell help system is crucial for users to learn commands and effectively administer systems.
— Skipping help files leads to inefficiency and frustration, akin to attempting complex tasks without using instruction manuals.
— Understanding commands can be achieved through reading help files, thus enhancing proficiency.

3.2. Updatable Help
— Starting from PowerShell v3, help files are not pre-installed but can be updated from the internet.
— Users must run PowerShell with elevated privileges to update help content.
— Offline users can also obtain help files to distribute within their networks via Save-Help.

3.3. Asking for Help
— The main cmdlet used for accessing help is Get-Help.
— Users can utilize Help and Man functions, which provide access to help topics and manuals respectively.

3.4. Using Help to Find Commands
— The help system allows users to search for commands using wildcards, such as Help *log* to find event log-related cmdlets.
— Tab completion and wildcard usage improve the command discovery process.

3.5. Interpreting the Help
— Help files follow specific conventions that provide information on command syntax, parameters, and examples.
— Key aspects include parameter sets, mandatory versus optional parameters, and the use of positional parameters.

3.6. Accessing “About” Topics
— Users can access general PowerShell documentation (about_ topics) through help commands.
— Example: Help *common* retrieves common parameter information.

3.7. Accessing Online Help
— PowerShell provides an online help feature that can display the most updated information available through Microsoft’s TechNet.

3.8. Lab Activities
— Users are encouraged to engage with practical exercises, which include updating help, finding cmdlets, and retrieving examples to reinforce learning.

3.9. Lab Answers
— Sample solutions to the lab activities demonstrate the application of skills learned in the chapter, including commands for help systems, processes, and event log management.

This chapter reinforces that reading and utilizing the help system is fundamental for mastering PowerShell and effectively performing administrative tasks.

Section Summary
Overview This chapter highlights the significance of the PowerShell help system for user proficiency and command discoverability.
3.1. The Help System: Discovering Commands The help system aids users in learning commands, preventing inefficiency similar to not using instruction manuals.
3.2. Updatable Help Help files in PowerShell v3 and later can be updated online; elevated permissions are required for updates.
3.3. Asking for Help The Get-Help cmdlet is essential for accessing help topics and manuals.
3.4. Using Help to Find Commands The help system supports searching for commands using wildcards to enhance command discovery.
3.5. Interpreting the Help Help files follow conventions detailing command syntax, parameters, and examples.
3.6. Accessing “About” Topics Users can retrieve general PowerShell documentation through help commands for specific topics.
3.7. Accessing Online Help PowerShell offers online help that provides the latest information from Microsoft’s TechNet.
3.8. Lab Activities Practical exercises are provided to reinforce learning about help, cmdlets, and examples.
3.9. Lab Answers Sample solutions reflect the application of learned skills in using help systems and command management.

Install Bookey App to unlock full text and audio

Chapter 4 | Running commands

Chapter 4: Running Commands

This chapter introduces PowerShell’s command execution, emphasizing its functionality as a shell rather than a traditional scripting language. The focus is on executing commands directly in the shell, using built-in cmdlets and external command-line utilities without needing to write scripts.

4.1. Not Scripting, but Running Commands
PowerShell operates as a shell, akin to Cmd.exe and UNIX shells. Users can simply type commands and parameters and see results immediately, rather than developing scripts. Although PowerShell accommodates advanced scripting complexities, beginners are encouraged to run commands directly for effectiveness.

4.2. The Anatomy of a Command
Understanding the structure of a PowerShell command is crucial. Key elements include:
— Cmdlet names follow a verb-noun format (e.g., Get-EventLog).
— Parameters can be named (with values) or switch parameters (without values).
— Accurate spacing, dashes, and parameter names are essential to avoid errors.

4.3. The Cmdlet Naming Convention
Cmdlets, native to PowerShell, follow a naming convention of verb followed by a noun (e.g., Get-Service). Microsoft’s standardization aids in anticipating command names, helping users guess and validate command functionality.

4.4. Aliases: Nicknames for Commands
Aliases provide shorter command names (e.g., gsv for Get-Service) and can be created or accessed in PowerShell. Unlike Linux, aliases in PowerShell do not carry parameters.

4.5. Taking Shortcuts
PowerShell allows command shortcuts in three ways:
Truncating Parameter Names: Use abbreviated names as long as they’re distinguishable.
Using Parameter Name Aliases: Some parameters have aliases not documented in help files.
Using Positional Parameters: Parameters can be provided by their position, but this method increases the risk of errors.

4.6. Cheating a Bit: Show-Command
The Show-Command cmdlet provides a graphical interface for constructing commands, making it easier to ensure correct syntax and usage.

4.7. Support for External Commands
PowerShell can execute traditional command-line utilities (e.g., Ping, Ipconfig) along with its cmdlets. Users are encouraged to continue using familiar commands when appropriate, while PowerShell also offers enhanced cmdlets for certain tasks.

4.8. Dealing with Errors
PowerShell generates error messages that often indicate the source of the problem, encouraging users to consult help and type commands accurately to find solutions.

4.9. Common Points of Confusion
Key common mistakes include:
— Incorrect formatting of cmdlet names and parameters.
— Forgetting spaces or dashes when typing commands can lead to errors.

4.10. Lab
Users are tasked with practical exercises to apply their understanding of command execution in PowerShell, such as listing processes, creating aliases, and querying firewall rules.

4.11. Lab Answers
Answers are provided for the lab tasks, reinforcing the concepts covered in the chapter and encouraging users to refine their command-line skills.

Section Description
Chapter 4: Running Commands Introduces PowerShell’s command execution as a shell, enabling users to execute commands directly.
4.1. Not Scripting, but Running Commands Encourages users to type commands directly instead of writing scripts, highlighting PowerShell’s shell functionality.
4.2. The Anatomy of a Command Describes the structure of a command, including cmdlet name format, parameters, and the importance of syntax.
4.3. The Cmdlet Naming Convention Cmdlets follow a verb-noun format which helps in predicting command names and functionality.
4.4. Aliases: Nicknames for Commands Explains how aliases provide shorter command names without parameters.
4.5. Taking Shortcuts Discusses methods of using abbreviated parameter names, parameter aliases, and positional parameters.
4.6. Cheating a Bit: Show-Command The Show-Command cmdlet offers a graphical interface for command construction.
4.7. Support for External Commands PowerShell can run traditional command-line utilities alongside its cmdlets.
4.8. Dealing with Errors Describes how PowerShell provides error messages that help identify and resolve issues.
4.9. Common Points of Confusion Lists common mistakes such as formatting errors and missing spaces or dashes.
4.10. Lab Practical exercises for applying command execution skills in PowerShell.
4.11. Lab Answers Provides answers to lab tasks to reinforce concepts and improve command-line skills.

Chapter 5 | Working with providers

Chapter 5. Working with Providers

Overview of Providers
PowerShell uses providers to manage various types of data storage, similar to how file systems work. Understanding this concept simplifies the use of PowerShell, especially for users already familiar with command prompts.

5.1. What are Providers?
A PowerShell provider (PSProvider) acts as an adapter to represent different data stores, such as the filesystem, environment variables, and the Windows Registry, as drives within PowerShell. Users can list installed providers with the `Get-PSProvider` command, which reveals each provider’s capabilities such as filtering and credential support.

5.2. Understanding Filesystem Organization
The Windows filesystem is structured around drives, folders, and files. PowerShell refers to these components as «items,» allowing for more generic operations that can apply to various data stores. This generic approach enables the use of item-related cmdlets across different providers.

5.3. Filesystem as a Model for Other Data Stores
PowerShell’s treatment of the filesystem serves as a model for other stores, including the Windows Registry. Although they share similarities, each form of storage has unique characteristics and operational support.

5.4. Navigating the Filesystem
Cmdlets like `Set-Location` help users navigate within the filesystem. PowerShell also provides the ability to create new items, but the cmdlet `New-Item` requires explicit type definitions for different item types, unlike the more user-friendly `mkdir` command.

5.5. Using Wildcards and Literal Paths
Wildcards are supported in many cmdlets, allowing users to specify multiple items with patterns. However, in cases where special characters are part of item names, the `-LiteralPath` parameter must be used to treat these characters literally.

5.6. Working with Other Providers
To gain proficiency with different providers, users can practice with the Registry provider, which is available on all systems. By navigating through the Registry structure, users can modify values similarly to how they would work with filesystem drives.

5.7. Lab
This section includes hands-on tasks for users to familiarize themselves with PowerShell commands related to providers, such as modifying Registry entries, creating directories, and understanding file content changes.

5.8. Further Exploration
PowerShell providers are also utilized in other software like IIS and SQL Server, which allows for dynamic interaction with their configurations. Users are encouraged to explore these providers to understand how different software systems implement provider concepts.

5.9. Lab Answers
The section provides solutions to the lab exercises, reinforcing the knowledge gained about cmdlets and providers while clarifying potential errors and their reasons.

This chapter emphasizes the importance of understanding providers in PowerShell for efficient data management and interaction with different types of storage systems.

Section Content Summary
Overview of Providers PowerShell uses providers to manage data storage, similar to file systems, simplifying user interaction.
5.1. What are Providers? PSProviders act as adapters representing different data stores as drives. Use `Get-PSProvider` to list capabilities.
5.2. Understanding Filesystem Organization The filesystem is organized into drives, folders, and files, referred to as «items,» enabling generic cmdlet usage.
5.3. Filesystem as a Model for Other Data Stores The filesystem serves as a model for other storage types like the Registry, each with unique characteristics.
5.4. Navigating the Filesystem Cmdlets like `Set-Location` aid navigation, while `New-Item` requires explicit type definitions for new items.
5.5. Using Wildcards and Literal Paths Wildcards allow pattern specification for multiple items; `-LiteralPath` is used for special characters in names.
5.6. Working with Other Providers Users can practice with the Registry provider to modify values similarly to filesystem operations.
5.7. Lab Hands-on tasks to practice PowerShell commands related to providers including modifying Registry entries.
5.8. Further Exploration Encourages exploration of providers in software like IIS and SQL Server to understand dynamic configuration interactions.
5.9. Lab Answers Provides solutions to lab exercises, reinforcing knowledge of cmdlets and addressing common errors.

Chapter 6 | The pipeline: connecting commands

Chapter 6: The Pipeline: Connecting Commands

In this chapter, the focus is on PowerShell’s unique capability to connect commands using a pipeline, enhancing the efficiency of command execution.

6.1 Connecting Commands
PowerShell enables the connection of multiple commands through a pipeline, allowing the output of one command to serve as the input for another. This feature distinguishes PowerShell from other shells, offering more modern implementation.

6.2 Exporting to CSV or XML
PowerShell commands like Get-Process, Get-Service, and Get-EventLog can easily export their output into CSV or XML formats.

* 6.2.1 Exporting to CSV
Using the pipeline, the command `Get-Process | Export-CSV procs.csv` allows you to export the process list to a CSV file, which can later be accessed and shared.

* 6.2.2 Exporting to XML
Similarly, the `Export-CliXML` cmdlet allows exporting data in an XML format. This format is versatile and can be read by various applications.

* 6.2.3 Comparing Files
The `Compare-Object` cmdlet (alias `Diff`) is utilized to compare two datasets, such as exported processes, assisting in identifying differences in process lists on different machines.

6.3 Piping to a File or Printer
PowerShell output can be redirected to files or printers using the `Out-File` cmdlet, providing options to specify character encoding and file widths.

6.4 Converting to HTML
PowerShell allows easy conversion of command output to HTML using `ConvertTo-HTML`. This can be followed by `Out-File` to save the HTML output to a file.

6.5 Using Cmdlets that Modify the System
PowerShell commands like `Stop-Process` can modify system state by interacting with processes and services. Caution is advised when connecting commands that alter system behavior.

6.6 Common Points of Confusion
New users may confuse file reading methods; using `Import-CSV` or `Import-CliXML` is recommended over `Get-Content` for proper data interpretation.

6.7 Lab
The chapter concludes with hands-on tasks reinforcing the concepts of exporting, comparing, and managing processes and services in PowerShell, ensuring users practice the learned commands.

6.8 Lab Answers
Provided answers guide users through the completion of the lab tasks, emphasizing practical application of chapter concepts.

Section Description
Chapter 6 The Pipeline: Connecting Commands — Focus on PowerShell’s capability to connect commands through a pipeline for efficient execution.
6.1 Connecting Commands — PowerShell connects multiple commands via a pipeline, allowing the output of one to be the input of another.
6.2 Exporting to CSV or XML — Commands can export data outputs into CSV or XML formats.
6.2.1 Exporting to CSV — Example: `Get-Process | Export-CSV procs.csv` exports process lists to CSV files.
6.2.2 Exporting to XML — The `Export-CliXML` cmdlet exports data in XML format, readable by various applications.
6.2.3 Comparing Files — The `Compare-Object` cmdlet (alias `Diff`) compares datasets to identify differences.
6.3 Piping to a File or Printer — The `Out-File` cmdlet redirects output to files or printers with options for encoding and width.
6.4 Converting to HTML — Command output can be converted to HTML using `ConvertTo-HTML`, followed by saving with `Out-File`.
6.5 Using Cmdlets that Modify the System — Commands like `Stop-Process` can alter system states, requiring caution.
6.6 Common Points of Confusion — New users should prefer `Import-CSV` or `Import-CliXML` over `Get-Content` for proper data interpretation.
6.7 Lab — Hands-on tasks to reinforce exporting, comparing, and managing processes in PowerShell.
6.8 Lab Answers — Provided to guide users through lab tasks for practical application of chapter concepts.

Install Bookey App to unlock full text and audio

1000 + Book Summaries ,   80 + Topics

1000 + Book Summaries ,

80 + Topics

New titles added every week

Chapter 7 | Adding commands

Chapter 7: Adding Commands

Overview
PowerShell’s extensibility is accentuated through various commands developed for Microsoft products. These can be accessed through management tools like Exchange Server and SQL Server.

7.1 How One Shell Can Do Everything
— PowerShell and the Microsoft Management Console (MMC) share extensibility.
— MMC requires additional components called snap-ins, similar to how PowerShell requires extensions.
— When management tools are installed, their corresponding PowerShell extensions become available.

7.2 About Product-Specific “Management Shells”
— There is only one version of Windows PowerShell, regardless of the product.
— Example: The Active Directory Module runs within standard PowerShell but includes preloaded commands for convenience.

7.3 Extensions: Finding and Adding Snap-ins
— PowerShell extensions come as snap-ins (PSSnapins) and modules.
— You can view registered snap-ins using `Get-PSSnapin -registered`.
— Load a snap-in using `Add-PSSnapin`, and explore added cmdlets with `Get-Command`.

7.4 Extensions: Finding and Adding Modules
— Modules are easier to manage and do not require advanced registration.
— PowerShell auto-discovers modules via PSModulePath.
— Commands from modules can be used without preloading them explicitly.

7.5 Command Conflicts and Removing Extensions
— Naming conventions with prefixes help avoid command conflicts.
— If conflicts arise, either `Remove-PSSnapin` or `Remove-Module` can be used to unload extensions.

7.6 On Non-Windows Operating Systems
— Some commands and modules may not function on Linux or macOS due to missing dependencies.

7.7 Playing with a New Module
— Experimenting with commands in PowerShell to discover functionalities (e.g., clearing DNS cache).

7.8 Profile Scripts: Preloading Extensions When the Shell Starts
— To streamline shell usage, create a profile script that loads necessary snap-ins and modules upon startup.

7.9 Getting Modules from the Internet
— PowerShellGet simplifies searching, installing, and updating modules from online repositories like PowerShell Gallery.

7.10 Common Points of Confusion
— New users often fail to utilize the help system effectively; using the `-example` or `-full` switches enhances learning.

7.11 Lab
— Task: Run Networking troubleshooting pack on supported Windows versions and troubleshoot connectivity using PowerShell.

7.12 Lab Answers
— Suggested commands for accomplishing the lab task, highlighting the discovery of relevant modules and commands.

Chapter 8 | Objects: data by another name

Chapter 8: Objects: Data by Another Name

In this chapter, we explore the critical concept of objects within PowerShell, which can be confusing but is vital for effective use of the shell. Readers with programming experience can skip to section 8.2, while novices should start from section 8.1.

8.1 What are Objects?
When you run commands like `Get-Process`, PowerShell returns a set of information about processes constructed in memory as a table. Each row (object) corresponds to a process, with columns (properties) representing various information attributes. PowerShell limits the visible columns based on its configuration, but using `ConvertTo-HTML` allows you to view all properties available for an object. Key terminology includes:
Object: A row in the table representing a single entity, like a process.
Property: A column in the table representing attributes of the object.
Method: Actions that can be performed on objects, such as killing a process.
Collection: The entirety of objects, equating to the table.

8.2 Understanding Why PowerShell Uses Objects
PowerShell uses objects because Windows is an object-oriented operating system, which makes this structure more intuitive and powerful for users. By leveraging objects, PowerShell reduces the need for complex text manipulation typically seen in UNIX/Linux, allowing for simpler and more efficient command execution without dependency on output formatting or text parsing.

8.3 Discovering Objects: Get-Member
To understand the properties and methods available for an object, you use `Get-Member` (alias `Gm`). This command reveals a list of an object’s members—properties and methods—allowing administrators to effectively manipulate and understand the objects they are working with.

8.4 Using Object Attributes, or Properties
In PowerShell, objects can contain different types of properties, including ScriptProperty, NoteProperty, and AliasProperty. Generally, properties provide descriptive values about an object. Most properties are read-only in PowerShell, with about 90% of usage revolving around retrieving these properties.

8.5 Using Object Actions, or Methods
Objects often have methods that allow users to execute actions on them, although casual PowerShell users typically interact with cmdlets rather than directly calling methods. This book focuses on using cmdlets for task management and simplifies the process for users.

8.6 Sorting Objects
PowerShell’s `Sort-Object` cmdlet allows sorting of object collections in a defined order. For example, you can sort processes by virtual memory usage in descending order. This cmdlet supports sorting by multiple properties as well.

8.7 Selecting the Properties You Want
The `Select-Object` cmdlet lets users specify which properties to display from an object, helping to filter out undesired data. It also allows for selecting a subset of objects with `-First` and `-Last` parameters.

8.8 Objects Until the End
The pipeline in PowerShell retains objects throughout the processing of a command line until the final command executes. Understanding how objects transition through the pipeline is essential, enabling users to manipulate data effectively at each stage.

8.9 Common Points of Confusion
New users often make mistakes in understanding object properties and handling commands. It’s important to remember to use `Gm` to view properties and to ensure proper syntax in command lines.

8.10 Lab
This section includes hands-on exercises designed to reinforce the concepts covered in the chapter, encouraging experimentation with various cmdlets.

8.11 Lab Answers
The answers provided to the lab exercises help users verify their understanding of the material and clarify any concepts that may be confusing.

Chapter 9 | The pipeline, deeper

Chapter 9: The Pipeline, Deeper

9.1. The Pipeline: Enabling Power with Less Typing
PowerShell’s pipeline allows administrators to execute complex tasks with minimal typing. This chapter emphasizes maximizing pipeline use to avoid using verbose scripts, enhancing efficiency in command execution.

9.2. How PowerShell Passes Data Down the Pipeline
When chaining commands, PowerShell ensures the output of the first command (Command A) is accepted by the second command (Command B) through a process called pipeline parameter binding. This allows seamless data transfer between commands.

9.3. Plan A: Pipeline Input ByValue
Pipeline input ByValue allows PowerShell to determine if a command’s output type (like strings) matches any parameter of the receiving command. However, if the types do not align, it may not work as expected.

9.4. Plan B: Pipeline Input ByPropertyName
If ByValue fails, PowerShell attempts to connect output to parameters using ByPropertyName. It checks for matching property names in the objects output by Command A and the parameters of Command B.

9.5. When Things Don’t Line Up: Custom Properties
Issues arise when the output from one command doesn’t match the expected parameter names of another. This section illustrates how to transform data, using Select-Object to create custom properties that align with another command’s expected inputs without manual alteration of source data.

9.6. Parenthetical Commands
Sometimes parameters don’t accept pipeline input. Parenthetical commands allow you to execute a command first and feed its output directly into a parameter, simplifying the data handling process.

9.7. Extracting the Value from a Single Property
If a command produces objects that aren’t directly usable by another command, you can use -ExpandProperty to extract specific property values. This provides a simple string output suitable for parameters requiring straightforward input types.

9.8. Lab
The lab section provides practical tasks to reinforce concepts learned about pipeline input, parameter binding, and using parenthetical commands. The exercises focus on using PowerShell commands to manipulate data successfully.

9.9. Further Exploration
Encourages further study of pipeline input concepts, emphasizing the differences in behavior between selecting properties and expanding them. Provides resources for additional help.

9.10. Lab Answers
Summarizes the correct responses and logic behind commands pertaining to pipeline input and parameter compatibility, consolidating understanding of the principles taught in the chapter.

Install Bookey App to unlock full text and audio

Chapter 10 | Formatting—and why it’s done on the right

Chapter 10: Formatting—and Why It’s Done on the Right

Overview of PowerShell Formatting
PowerShell cmdlets produce objects with potentially numerous properties, not all of which are displayed by default. Users can utilize `Get-Member` to see a full list of properties and `Select-Object` to choose specific ones. This chapter focuses on customizing output formatting, enabling users to override default configurations.

10.1. Formatting: Making What You See Prettier
While PowerShell is not a comprehensive reporting tool, it can effectively gather and format information for reports. This section explains how the PowerShell formatting system works and highlights common traps new users may encounter.

10.2. Working with the Default Formatting
The default display of cmdlet outputs includes specific column headers and alignments determined by `.format.ps1xml` files. For example, the formatting for process objects is found in `DotNetTypes.format.ps1xml`. Users are guided to navigate this XML file to understand the intrinsic formatting rules.

10.3. Formatting Tables
The `Format-Table` cmdlet, or its alias `Ft`, is key for daily formatting tasks. Important parameters include:
— `-autoSize` for adjusting column widths automatically.
— `-property` to specify which properties to include.
— `-groupBy` to create new column headers based on property values.
— `-wrap` to prevent truncation of information.

10.4. Formatting Lists
The `Format-List` cmdlet (`Fl`) is used to display detailed property information vertically, ideal for instances where horizontal space is limited.

10.5. Formatting Wide Lists
`Format-Wide` (`Fw`) presents a single property’s values across multiple columns, useful for quickly viewing lists of items.

10.6. Creating Custom Columns and List Entries
Custom properties can be added to the output using hash tables, allowing users to re-label columns or perform calculations directly in the output.

10.7. Going Out: To a File, a Printer, or the Host
Formatted output can be directed to various destinations: the console (Out-Host), files (Out-File), or printers (Out-Printer). It is vital to follow the correct configuration to ensure the output appears as intended.

10.8. Another Out: GridViews
`Out-GridView` displays output in a grid format, bypassing the formatting subsystem, which enhances readability for handling larger datasets.

10.9. Common Points of Confusion
Two major pitfalls include:
Always Format Right: `Format-` cmdlets should be the last command in a pipeline, except when followed by `Out-File` or `Out-Printer`.
One Type of Object at a Time: Mixing different object types can lead to improper formatting results.

10.10. Lab
A series of tasks encourages readers to practice new formatting skills using various cmdlets and configurations.

10.11. Further Exploration
Encouragement to experiment with formatting capabilities in PowerShell to enhance proficiency and prepare for future labs.

10.12. Lab Answers
A collection of solutions to the lab exercises provides users with clear examples to check their understanding and skills.

Chapter 11 | Filtering and comparisons

Chapter 11: Filtering and Comparisons

In this chapter, you’ll learn how to narrow down the output in PowerShell to focus on specific items of interest rather than working with the entire dataset.

11.1. Making the Shell Give You Just What You Need

PowerShell offers two primary filtering methods:
Early Filtering: Instruct cmdlets to retrieve only the specified data.
Iterative Filtering: Use a second cmdlet to filter unwanted results after retrieving all data.

For example, to get only running services with `Get-Service`, you’d use a command like `Get-Service | Where-Object { $_.Status -eq ‘Running’ }`.

11.2. Filtering Left

Filtering left means applying your filtering criteria as early in the command as possible to minimize the workload on subsequent cmdlets. Each cmdlet can have different filtering abilities. Knowing how to effectively filter can lead to better performance but may require a deeper understanding of cmdlet functionalities.

11.3. Using Comparison Operators

Comparison operators allow you to test relationships between values, yielding Boolean results (True or False). The common PowerShell comparison operators include:
— `-eq` (equal), `-ne` (not equal)
— `-gt`, `-lt` (greater than, less than)
— Comparison for strings: `-like`, `-notlike`, `-match`, `-notmatch`.

Boolean operators such as `-and`, `-or`, and `-not` can evaluate multiple conditions together.

11.4. Filtering Objects Out of the Pipeline

You can apply filters directly using cmdlets like `Where-Object`. This allows you to filter as objects pass through the pipeline, e.g., `Get-Service | Where-Object { $_.Status -eq ‘Running’ }`. The `$_.` represents the current object in the pipeline.

11.5. Using the Iterative Command-Line Model

The PowerShell Iterative Command-Line Model enables you to build commands step-by-step, testing results after each command. This method encourages active engagement with output, refining commands iteratively.

11.6. Common Points of Confusion

Filter Left: Always try to filter as close to the source of data as possible.
Deferred Placeholders (`$_`): This placeholder is only valid in specific contexts (like `Where-Object`).

11.7. Lab

The lab includes exercises focused on filtering tasks such as retrieving non-virtual network adapters, DNS client cache records, and specific hotfixes.

11.8. Further Exploration

Practice filtering the output from previously learned cmdlets (e.g., `Get-Hotfix`, `Get-Process`). Challenge yourself to use filtering effectively and to identify when to use `Where-Object`.

11.9. Lab Answers

A set of practical answers is provided for lab exercises focused on gaining familiarity with command syntax and filtering capabilities.

Chapter 12 | A practical interlude

Chapter 12: A Practical Interlude

This chapter focuses on applying the knowledge gained throughout the book by walking through a real-world PowerShell example, emphasizing self-teaching and problem-solving skills.

12.1. Defining the Task

The task involves modifying user privileges on a Windows system with PowerShell version 5 or later. It excludes Linux or macOS due to differing user privilege concepts.

12.2. Finding the Commands

To identify the relevant commands, the process begins with keyword searches. Initial attempts using `help` and `get-command` reveal no relevant commands, prompting a search in the online PowerShell Gallery. The module ‘PoshPrivilege’ is found and installed after review for safety.

12.3. Learning to Use the Commands

After installing, the available commands are examined using `get-command`. The presence of help documentation aids in understanding the command syntax and options. The chapter demonstrates how to add a user privilege using the `Add-Privilege` command, confirming its effectiveness with the `Get-Privilege` command.

12.4. Tips for Teaching Yourself

The chapter outlines essential self-teaching strategies:
— Utilize help files and their examples instead of relying solely on external sources.
— Be attentive to all displayed information, as everything can contribute to problem-solving.
— Embrace experimentation in a virtual machine to foster learning and confidence.

12.5. Lab

Readers are tasked with creating and sharing a directory named «LABS» on a Windows machine running PowerShell v3 or later, ensuring the appropriate share permissions.

12.6. Lab Answer

The lab concludes with a PowerShell script for creating the directory, sharing it, and retrieving its permissions, reinforcing the practical application of the concepts learned in this chapter.

Install Bookey App to unlock full text and audio

1000 + Book Summaries ,   80 + Topics

1000 + Book Summaries ,

80 + Topics

New titles added every week

Chapter 13 | Remote control: one-to-one, and one-to-many

Chapter 13: Remote Control: One-to-One and One-to-Many

Overview of PowerShell Remoting
— Early PowerShell versions had limited functionality with the `-computerName` parameter.
— PowerShell remoting allows any cmdlet to run on a remote machine without needing local cmdlet availability.
— Focus on practical usage scenarios, though remoting is a complex topic.

13.1 Remote PowerShell Concept
— Remote PowerShell operates similarly to Telnet, using WS-MAN over HTTP/HTTPS.
— WinRM facilitates this communication, installed by default on Windows operating systems.
— SSH-based remoting is now also supported, but this chapter primarily discusses WS-MAN.

13.2 WinRM Overview
— WinRM needs to be configured on receiving computers for remoting.
— It handles traffic and can be set up to listen for commands on defined ports.
— Enable remoting using `Enable-PSRemoting` for automatic configuration.

13.3 One-to-One Remoting
— One-to-one remoting provides a remote shell prompt via `Enter-PSSession`.
— Commands are run directly on the remote computer, with results returned back.
— Exiting remoting is done with `Exit-PSSession`.

13.4 One-to-Many Remoting
— `Invoke-Command` allows for issuing commands to multiple computers simultaneously.
— Syntax requires proper use of curly braces to define command scope.
— Supports automation via script files rather than individual commands.

13.5 Differences in Execution
— `Invoke-Command` executes commands in parallel and allows for efficient remote processing.
— Local and remote command executions differ, especially in output handling and efficiency.
— Emphasis on performing as much processing as possible on the remote machine.

13.6 Considerations for Persistent Connections
— Establishing reusable connections can improve efficiency for repeated tasks.
— Security considerations are important in corporate environments; RDP may be an alternative.

13.7 Session Options
— `-SessionOption` parameter in remoting commands allows tweaks in session behavior.

13.8 Common Confusions
— Remoting operates using real computer names; DNS aliases or IP addresses may not work.
— Proper domain configurations simplify remoting.
— Understand that subsequent commands begin afresh unless grouped within a single invocation.

13.9 Lab Activities
— Suggested lab tasks to experiment with one-to-one and one-to-many remoting functionality.

13.10 Further Exploration
— Recommend resources for deeper understanding, including a free mini e-book on PowerShell Remoting.

13.11 Lab Answers
— Offers solutions to the lab tasks to help validate understanding of the concepts discussed.

Chapter 14 | Using Windows Management Instrumentation and CIM

Chapter 14: Using Windows Management Instrumentation and CIM

Introduction
This chapter focuses on Windows Management Instrumentation (WMI) and its integration with PowerShell. WMI is a powerful tool for system information gathering but can be complex due to its documentation and functionality nuances. The chapter aims to clarify how to effectively use WMI through PowerShell and offers insights into overcoming its limitations.

14.1. WMI Essentials
WMI organizes vast amounts of management information into namespaces and classes. Each namespace functions as a directory for specific technologies, while classes represent manageable components. Users can query instances of these classes to retrieve system information, although the availability of classes varies by system.

14.2. The Bad News About WMI
Despite its potential, WMI has been inconsistently implemented across products, leading to confusion. Some classes are read-only, and not all components are accessible via WMI. Furthermore, documentation is often lacking, causing additional challenges for administrators.

14.3. Exploring WMI
Hands-on exploration of WMI can be facilitated through tools like WMI Explorer, allowing users to browse namespaces and classes more efficiently. Search engines also provide valuable resources for discovering the right WMI classes.

14.4. Choose Your Weapon: WMI or CIM
PowerShell v3 introduces both traditional WMI cmdlets and newer CIM cmdlets. The latter communicates over WS-MAN, providing a more modern and flexible option for accessing WMI data.

14.5. Using Get-WmiObject
The Get-WmiObject cmdlet retrieves instances from specified namespaces and classes, allowing users to filter results and view detailed properties. It offers a straightforward but slightly outdated method for interacting with WMI data.

14.6. Using Get-CimInstance
Get-CimInstance, introduced in PowerShell v3, offers a similar approach to Get-WmiObject but with improved syntax and functionality. It integrates better with modern systems and provides a cleaner method for accessing remote data.

14.7. WMI Documentation
Comprehensive documentation for WMI classes can often be found through web searches, particularly on Microsoft’s MSDN site. However, many users face challenges finding specific information.

14.8. Common Points of Confusion
Users often struggle with WMI’s filter criteria, which differs from standard PowerShell syntax. Additionally, WMI’s external nature means it doesn’t always behave like native PowerShell cmdlets.

14.9. Lab
The chapter includes practical exercises designed to familiarize users with querying WMI classes. Tasks focus on locating information such as IP addresses, operating systems, and service statuses.

14.10. Further Exploration
WMI is a complex technology deserving deeper study. Recommendations include resources that clarify its use and functionality, highlighting that the newer CIM cmdlets often simplify the experience.

14.11. Lab Answers
The chapter concludes with answers to the lab exercises, providing users with guidance on using WMI and CIM effectively to achieve their administrative goals.

Chapter 15 | Multitasking with background jobs

Chapter 15: Multitasking with Background Jobs

15.1 Making PowerShell Do Multiple Things at the Same Time
PowerShell typically operates as a single-threaded application, executing one command at a time. However, it can use background jobs to run commands on separate threads, allowing users to multitask. Commands can be moved to the background only before they’re executed. Once running, users can check job status and retrieve results.

15.2 Synchronous vs. Asynchronous
Commands run synchronously require users to wait for completion, while background jobs run asynchronously, allowing other tasks to proceed. Key differences include input handling, immediate error visibility, and how command results are displayed.

15.3 Creating a Local Job
Local jobs can be created with the Start-Job command, where the command runs mostly on the local machine. Parameters like -scriptblock and -name can be specified, and jobs can access remote computers if the right permissions are set.

15.4 WMI, as a Job
Using Get-WmiObject with the -AsJob parameter allows running WMI queries as background jobs. This approach enables efficient processing of multiple remote computers without the sequential delays typical of regular WMI queries.

15.5 Remoting, as a Job
Invoke-Command can also create jobs when combined with the -AsJob parameter. This allows commands to be run in parallel across multiple computers, improving performance and distributing workload efficiently.

15.6 Getting Job Results
The Get-Job cmdlet retrieves the status of all jobs, and Receive-Job is used to fetch results from a specific job. Job results can be cached or processed with additional cmdlets.

15.7 Working with Child Jobs
Jobs can have child jobs, which can also be monitored and managed. Users can retrieve results from these child jobs individually.

15.8 Commands for Managing Jobs
PowerShell provides commands such as Remove-Job, Stop-Job, and Wait-Job for managing and overseeing job statuses.

15.9 Scheduled Jobs
Scheduled jobs integrate with Windows Task Scheduler, allowing tasks to run at specified times. Outputs are stored on disk for later retrieval, distinguishing them from traditional background jobs.

15.10 Common Points of Confusion
Misusing commands that launch jobs might lead to confusion, especially regarding connectivity and job visibility across user sessions. Normal jobs are not visible across different users.

15.11 Lab
Various exercises encourage users to create background jobs, utilize remote computers, and schedule jobs while learning through practical applications.

15.12 Lab Answers
The lab section includes practical solutions for creating and managing jobs in PowerShell, demonstrating the concepts covered throughout the chapter.

Section Description
15.1 Making PowerShell Do Multiple Things at the Same Time PowerShell is typically single-threaded but can use background jobs to multitask by executing commands on separate threads.
15.2 Synchronous vs. Asynchronous Synchronous commands require waiting for completion, while asynchronous background jobs allow other tasks to proceed.
15.3 Creating a Local Job Local jobs can be created using Start-Job with parameters like -scriptblock and -name, and can access remote computers with permissions.
15.4 WMI, as a Job The Get-WmiObject command with the -AsJob parameter allows running WMI queries as background jobs, improving efficiency.
15.5 Remoting, as a Job Invoke-Command can create parallel jobs across multiple computers when used with the -AsJob parameter.
15.6 Getting Job Results The Get-Job cmdlet retrieves job status, while Receive-Job fetches results from specific jobs.
15.7 Working with Child Jobs Child jobs can be monitored and managed, with results retrievable individually.
15.8 Commands for Managing Jobs Commands such as Remove-Job, Stop-Job, and Wait-Job are used for job management in PowerShell.
15.9 Scheduled Jobs Scheduled jobs use Windows Task Scheduler to run tasks at specific times, with outputs stored on disk.
15.10 Common Points of Confusion Misuse of job commands may cause confusion about connectivity and job visibility across user sessions.
15.11 Lab Practical exercises to create background jobs, use remote computers, and schedule jobs for hands-on learning.
15.12 Lab Answers Practical solutions for creating and managing PowerShell jobs are provided, illustrating chapter concepts.

Install Bookey App to unlock full text and audio

Chapter 16 | Working with many objects, one at a time

Chapter 16: Working with Many Objects, One at a Time

This chapter focuses on automating administration tasks in PowerShell, specifically dealing with multiple targets. Key techniques are demonstrated for executing tasks across batch cmdlets, WMI (Windows Management Instrumentation), and object enumeration.

16.1 Automation for Mass Management

Concept Overview: Introduces the idea of managing multiple objects simultaneously (mass management).
Example: A comparison is made with VBScript where a `For Each` loop is used to process multiple items one by one.

16.2 The Preferred Way: “Batch” Cmdlets

Batch Administration: Emphasizes the importance of using batch cmdlets which handle collections of objects efficiently.
Examples: Commands such as `Get-Service` piped to `Set-Service` for changing service settings across multiple machines are detailed. The `-passThru` parameter is introduced for output verification.

16.3 The CIM/WMI Way: Invoking Methods

Using WMI: Discusses the challenge when there’s no cmdlet available to perform an action on WMI objects.
Example Process: Walks through enabling DHCP for Intel network adapters using WMI, demonstrating how to retrieve configurations and invoke methods like `EnableDHCP` through `Invoke-WmiMethod`.

16.4 The Backup Plan: Enumerating Objects

Fallback Method: Describes when to revert to enumerating objects using cmdlets like `ForEach-Object` when other methods fail.
Illustrative Command: Uses the `Change()` method on WMI services with a detailed example showcasing handling service password changes.

16.5 Common Points of Confusion

Which Method to Use: Clarifies the choice between batch cmdlets and WMI methods based on the retrieval method of the objects.
WMI Methods vs. Cmdlets: Distinguishes when to use each, recommending `ForEach-Object` for executing methods when no cmdlet exists.
Documentation of Methods: Emphasizes that PowerShell’s built-in help doesn’t cover methods well, recommending online searches for detailed documentation.

16.6 Lab

Practice Exercises: Encourages readers to answer questions related to methods in ServiceController and Process objects, and demonstrate the use of PowerShell to manipulate these objects.

16.7 Lab Answers

Answers Provided: Gives correct answers to the lab questions, reinforcing the knowledge and providing references to commands and methods covered in the chapter.

This chapter illustrates various effective techniques for managing multiple objects in PowerShell, emphasizing the importance of batch processing and understanding WMI.

Chapter 17 | Security alert!

Chapter 17: Security Alert!

In this chapter, we explore the security implications of PowerShell and how to balance security with its powerful capabilities.

17.1 Keeping the Shell Secure

PowerShell, introduced in 2006, has a rich scripting capability. However, it was developed post the Trustworthy Computing Initiative, ensuring better security compared to its predecessors like VBScript. PowerShell’s security relies on existing user permissions; if a user lacks permissions through other means, PowerShell cannot override them. The focus is preventing unintentional script execution rather than stopping determined actions by knowledgeable users.

17.2 Windows PowerShell Security Goals

PowerShell does not add extra permission layers; it operates within the existing security framework. If a user can’t perform an action via traditional means, they can’t perform it in PowerShell either. The system primarily prevents users from accidentally executing untrusted scripts and is not a layer of defense against malware once it is present on a system.

17.3 Execution Policy and Code Signing

The execution policy restricts script execution by default, preventing script runs without explicit configuration. The five execution policy settings include:
Restricted: No scripts run.
AllSigned: Only scripts with a valid digital signature run.
RemoteSigned: Local scripts run; remote scripts must be signed.
Unrestricted: All scripts run.
Bypass: For application developers; does not enforce any policy.

It is emphasized that execution policy is for protecting uninformed users and does not prevent knowledgeable users from executing commands intentionally.

17.3.2 Digital Code Signing

Digital code signing helps verify the source of scripts. A valid code-signing certificate is essential to sign scripts securely. This certificate acts as a digital ID for organizations, providing assurance about the script’s integrity and origin.

17.4 Other Security Measures

PowerShell includes fundamental security measures, such as treating .PS1 files as non-executables and requiring scripts to be called with a specific path, thus preventing easy execution which could lead to command hijacking.

17.5 Other Security Holes?

PowerShell’s design doesn’t prevent users from manually typing potentially harmful commands. The focus is on preventing unintentional running of scripts, but knowledgeable users can still execute harmful commands through various means.

17.6 Security Recommendations

For optimal balance, Microsoft suggests using RemoteSigned or AllSigned execution policies. Users can create self-signed certificates for internal use and should sign scripts regularly. Importantly, users should maintain caution with unverified scripts, ensuring proper review before execution.

17.7 Lab

The lab encourages users to enable script execution using the Set-ExecutionPolicy cmdlet, primarily suggesting the RemoteSigned policy while being mindful of organizational security policies.

Chapter 18 | Variables: a place to store your stuff

Chapter 18: Variables: A Place to Store Your Stuff

18.1. Introduction to Variables
Variables in PowerShell are like boxes that store various types of data. They are easy to use; you don’t need to declare them explicitly, and their contents can change types freely. Variables can hold single items or collections, and accessing them is straightforward.

18.2. Storing Values in Variables
Everything in PowerShell is treated as an object, including simple strings. You can create a variable and assign it a value using the equals sign. Variable names start with a dollar sign and may include letters, numbers, or underscores, but they should be meaningful. Variables are not persistent after closing the shell.

18.3. Using Variables: Fun Tricks With Quotes
Using single quotes treats strings literally, while double quotes allow for variable substitution. The backtick (`) serves as an escape character to negate or add special meanings to following characters.

18.4. Storing Many Objects in a Variable
You can use a comma-separated list to assign multiple values to a single variable. Access individual elements with index notation. Methods can be applied to single or multiple objects, with PowerShell v3 simplifying this with automatic unrolling for properties.

18.5. More Tricks With Double Quotes
Double quotes allow for more complex operations, like extracting specific properties from objects in a collection using subexpressions.

18.6. Declaring a Variable’s Type
You can declare a specific data type for your variables to prevent errors and ensure they hold the intended data type. This process involves placing the desired type in square brackets before the variable assignment.

18.7. Commands for Working with Variables
PowerShell provides commands like `New-Variable`, `Set-Variable`, and `Remove-Variable` for explicit variable management but typically, ad hoc syntax is sufficient for most users.

18.8. Variable Best Practices
Keep variable names meaningful but concise, avoid spaces, and declare types when necessary for clarity and error prevention.

18.9. Common Points of Confusion
Students often confuse the dollar sign with a variable name. Remember, it indicates that what follows is a variable reference, not part of the name itself.

18.10. Lab
Tasks include creating a background job, capturing its results in a variable, displaying them, and exporting them to a file.

18.11. Further Exploration
Explore previous chapters for potential variable applications in earlier topics, enhancing the utility and reusability of your code.

18.12. Lab Answers
Provided commands for completing the lab tasks, ensuring hands-on practice with the concepts discussed in the chapter.

Install Bookey App to unlock full text and audio

1000 + Book Summaries ,   80 + Topics

1000 + Book Summaries ,

80 + Topics

New titles added every week

Chapter 19 | Input and output

Chapter 19: Input and Output

Overview
This chapter focuses on managing input and output in PowerShell, particularly while creating scripts that interact with users. It emphasizes that techniques discussed here are for scripts that require human interaction, not for unattended scripts.

19.1. Prompting for and Displaying Information
PowerShell operates through various host applications (like console and ISE), affecting how it prompts for information and displays output. Each host application (console, ISE, third-party editors) uses different methods for input collection and output display.

19.2. Read-Host
The Read-Host cmdlet collects text input from users via a prompt. It can be used to store user input in a variable. The graphical representation of input may vary across PowerShell versions and hosts. For graphical input boxes, .NET Framework can be used to load Visual Basic components.

19.3. Write-Host
Write-Host displays output directly to the screen without passing through the pipeline. It allows for color formatting but should only be used for messages directed at users, as it cannot capture output for further processing. Instead, Write-Verbose or other cmdlets are recommended for standard output.

19.4. Write-Output
Write-Output sends objects into the pipeline, allowing further processing or filtering. Unlike Write-Host, it doesn’t directly display output but relies on the pipeline’s processing to show results.

19.5. Other Ways to Write
PowerShell includes several cmdlets (e.g., Write-Warning, Write-Verbose, Write-Debug, Write-Error) to produce output that can be suppressed through configuration variables. These cmdlets can enhance the output experience, especially concerning warnings, messages, and debugging info.

19.6. Lab
The lab exercises encourage readers to practice using Write-Host and Write-Output by displaying calculations, prompting for user input, and filtering results based on user input criteria.

19.7. Further Exploration
Readers should familiarize themselves with the cmdlets introduced in this chapter and consult their help files for deeper understanding. Regular practice will enhance proficiency with user input and output management in PowerShell.

19.8. Lab Answers
This section provides sample answers for the lab tasks, reinforcing the techniques learned in the chapter.

Chapter 20 | Sessions: remote control with less work

Chapter 20: Sessions — Remote Control with Less Work

In this chapter, we explore PowerShell’s remoting features, specifically focusing on making remote connections easier and more reusable through sessions.

20.1. Making PowerShell Remoting Easier

Connecting to remote computers often involves repeating the specification of computer names, credentials, and other parameters. To simplify this process, reusable sessions are introduced, allowing for persistent connections without constant reconfiguration.

20.2. Creating and Using Reusable Sessions

A session is a persistent link between a local PowerShell instance and a remote one. PowerShell maintains a list of opened sessions which can be used to execute commands. Sessions are created using the `New-PSSession` cmdlet and can be stored in variables to streamline future operations. It is crucial to manage resources by closing sessions when no longer needed, using `Remove-PSSession`.

20.3. Using Sessions with Enter-PSSession

The `Enter-PSSession` cmdlet allows users to engage in a remote interactive shell with a single remote computer by specifying a session object. For convenience, session objects can be filtered and accessed through specific properties, or retrieved directly using `Get-PSSession` if you forget index numbers.

20.4. Using Sessions with Invoke-Command

`Invoke-Command` is a powerful feature that allows for parallel command execution across multiple remote machines via sessions. This method simplifies command execution while handling process workload independently, enhancing efficiency.

20.5. Implicit Remoting: Importing a Session

Implicit remoting allows users to execute commands from a remote module without installing it locally. It involves establishing a session with a remote machine, importing commands with a prefix to avoid conflicts, and executing them as if they were local.

20.6. Using Disconnected Sessions

PowerShell v3 introduced disconnected sessions, which remain active even after disconnection from the remote machine. Users can manage these sessions and configure settings through the WSMan drive, ensuring control over idle timeouts and active connections.

20.7. Lab Exercise

A lab exercise is provided to practice creating sessions, using remote shells, executing commands, and importing modules, demonstrating the practical applications of remoting techniques in a controlled environment.

20.8. Further Exploration

Readers are encouraged to assess their environments for PowerShell-enabled products, as many can be managed through remoting capabilities.

20.9. Lab Answers

Detailed answers are provided to the lab activities, allowing users to verify their understanding and application of PowerShell remoting techniques.

Chapter 21 | You call this scripting?

Chapter 21: You Call This Scripting?

Introduction to Scripting in PowerShell
This chapter addresses how PowerShell scripting is a powerful tool for automating tasks, allowing users to avoid repetitive command typing. Scripting should be seen as a straightforward means of improving efficiency rather than complex programming.

21.1 Not Programming, More Like Batch Files
PowerShell scripts function similarly to traditional batch files (.BAT or .CMD). They are lists of commands that can be executed in order. Using the PowerShell ISE improves the scripting experience, making it simpler to craft and run scripts without excessive retyping.

21.2 Making Commands Repeatable
Scripts are designed to facilitate running commands multiple times without retyping them. The chapter showcases how to create a sample script using WMI commands to retrieve and display disk inventory information, aiming for clarity and ease of modification.

21.3 Parameterizing Commands
To cater to varying needs, scripts can be parameterized. The chapter emphasizes the importance of defining variables for elements that may change, enhancing usability, especially for users less familiar with PowerShell.

21.4 Creating a Parameterized Script
The process of creating parameters in scripts is described, allowing users to specify new values easily. Scripts can accept multiple parameters, providing flexibility in how they are executed.

21.5 Documenting Your Script
Good documentation is essential for scripts. PowerShell allows users to incorporate comment-based help directly within the script. This feature enables users to view help information just as they would for native cmdlets.

21.6 One Script, One Pipeline
A key distinction is made regarding how commands execute within scripts compared to the command line. In a script, all commands run in a single pipeline, which affects output formatting and requires careful consideration of what is returned.

21.7 A Quick Look at Scope
The concept of scope is explored, explaining how variables exist within certain contexts in PowerShell. The distinction between global and script scopes and how they influence variable accessibility is crucial for script development.

21.8 Lab
An exercise invites users to create their scripts using concepts covered in the chapter, focusing on parameterization and incorporating comment-based help. Users should test their scripts to ensure proper functionality.

21.9 Lab Answer
Example code and explanation are provided, demonstrating how to create a script that retrieves disk information while using parameters for computer name and minimum free space thresholds.

Install Bookey App to unlock full text and audio

Chapter 22 | Improving your parameterized script

Chapter 22: Improving Your Parameterized Script

22.1 Starting Point
In this section, the chapter establishes a starting point with a parameterized script, `Get-DiskInventory.ps1`, which retrieves logical disk information using WMI. The script includes comment-based help and two input parameters: `computername` and `drivetype`. The output is modified to show selected objects rather than a formatted table, enhancing flexibility for future data exports.

22.2 Getting PowerShell to Do the Hard Work
Adding `[CmdletBinding()]` at the beginning of the script transforms it into an advanced script, enabling additional PowerShell capabilities. This enhancement allows for better handling of parameters and output options while maintaining the script’s core functionality.

22.3 Making Parameters Mandatory
The chapter suggests making the `-ComputerName` parameter mandatory instead of providing a default value. This prompts users for the required input, enhancing clarity and usability. The `Param()` block syntax is explained for better understanding, including how to define mandatory parameters and specify data types.

22.4 Adding Parameter Aliases
To improve usability, aliases can be added to parameters. The parameter `-computername` receives the alias `-hostname`, allowing users to reference the parameter in a way that might be more intuitive for them.

22.5 Validating Parameter Input
The chapter discusses validating the input for the `-drivetype` parameter to ensure that only acceptable values (2 and 3) are used. This validation prevents errors by restricting acceptable input according to the WMI class specifications.

22.6 Adding the Warm and Fuzzies with Verbose Output
Introducing `Write-Verbose` allows scripts to communicate progress more effectively than using `Write-Host`. The chapter shows how to implement verbose output to inform users about the script’s actions, enhancing its interactivity and usability.

22.7 Lab
The lab exercise tasks the reader with creating a new script named `Get-PhysicalAdapters.ps1`, requiring the parameterization of the `-computerName`, making it mandatory, adding an alias, and including verbose output.

22.8 Lab Answer
The chapter concludes with a sample solution for the lab, showcasing a well-documented and parameterized script that retrieves physical network adapter information from a specified computer, utilizing the skills learned throughout the chapter.

Chapter 23 | Advanced remoting configuration

Chapter 23: Advanced Remoting Configuration

In this chapter, we explore the advanced features of PowerShell remoting that were not covered in Chapter 13. While not all features will be applicable to everyone, it is important to be aware of them for future use. The content focuses on PowerShell v3 and later versions.

23.1. Using Other Endpoints

PowerShell allows multiple endpoints (session configurations) per computer. The default endpoint for remoting commands is «Microsoft.PowerShell,» which corresponds to the 64-bit shell on a 64-bit machine, with an additional «Microsoft.PowerShell32» for backward compatibility.

To connect to an alternative endpoint, use the `-ConfigurationName` parameter in commands like `Enter-PSSession`.

23.2. Creating Custom Endpoints

Creating a custom endpoint involves two main steps:
1. Creating a Session Configuration File: Utilize `New-PSSessionConfigurationFile` to define an endpoint’s characteristics, such as commands and capabilities.
2. Registering the Session Configuration: Use `Register-PSSessionConfiguration` to load the file into the WinRM service, where you can also set user connection permissions.

An example is given for creating an endpoint for a HelpDesk group with restricted access, only allowing them to see network adapter management commands without granting them permissions.

23.3. Enabling Multihop Remoting

Multihop remoting allows connection to multiple computers in sequence. By default, PowerShell can only delegate credentials for one hop. To enable multihop, perform the following on the respective computers:
1. For the client: `Enable-WSManCredSSP -Role Client -DelegateComputer

`
2. For the server: `Enable-WSManCredSSP -Role Server`.

These settings can also be managed via Group Policy.

23.4. Digging Deeper into Remoting Authentication

PowerShell uses mutual authentication, ensuring the remote machine verifies its identity to the user. This is crucial for security, as it prevents impersonation through DNS spoofing.

23.4.1. Defaults for Mutual Authentication

Most PowerShell usage assumes an Active Directory environment for mutual authentication, which requires resolving a computer name to an accurate IP address.

23.4.2. Mutual Authentication via SSL

To use SSL for mutual authentication:
— Obtain an SSL certificate issued to the destination machine.
— Install it under the computer account’s Personal certificate store and create an HTTPS listener.

23.4.3. Mutual Authentication via TrustedHosts

Using TrustedHosts is simpler than SSL but compromises security. It disables mutual authentication for specified hosts. Configure TrustedHosts in Local Security Policy or Group Policy for trusted environments, remembering to include the `-Credential` parameter in remoting commands.

23.5. Lab

Create a remoting endpoint named «TestPoint» that loads the SmbShare module and restricts visibility to only the `Get-SmbShare` cmdlet. Test the connection using `Enter-PSSession` to ensure only the allowed commands are accessible.

23.6. Lab Answer

An example is provided to create the configuration and register it successfully. Users can then enter the restricted endpoint and run `Get-Command`.

Chapter 24 | Using regular expressions to parse text files

Chapter 24: Using Regular Expressions to Parse Text Files

Overview
Regular expressions (regex) are crucial for text parsing, especially in UNIX/Linux environments, but less commonly used in PowerShell. This chapter focuses on using regex in PowerShell to parse text files, particularly IIS log files, presenting a simplified introduction rather than a comprehensive guide due to the complexity of regex.

24.1. The Purpose of Regular Expressions
Regex defines text patterns, such as an IPv4 address or error codes in log files. They can detect and capture specific patterns to extract relevant information from larger texts.

24.2. A Regex Syntax Primer
A basic regex matches an exact string but also utilizes special characters to detect variable text patterns:
— `\w` matches word characters.
— `\d` matches digits, while `\D` matches nondigits.
— `.` represents any single character.
— `[]` and `[^]` define character sets or exclusions.
— Quantifiers `?`, `*`, and `+` control the number of character matches.
— Anchors `^` and `$` denote the start and end of strings, respectively.

Examples of regex patterns for practical use are provided, highlighting their flexibility in matching text formats.

24.3. Using Regex with -Match
The `-Match` operator in PowerShell checks if strings meet regex patterns, returning true or false based on matches. This section encourages practice with examples of string testing.

24.4. Using Regex with Select-String
The chapter demonstrates the application of regex using `Select-String` with IIS log files to find HTTP 40x errors and specific user-agent strings. It explains how to construct regex patterns for various log formats and provides command-line examples for retrieving relevant data.

24.5. Lab
A set of exercises is provided for users to practice regex in PowerShell, including tasks like filtering files by name, finding processes, extracting specific lines from logs, and matching IPv4 addresses.

24.6. Further Exploration
Regular expressions are broadly applicable across PowerShell. The chapter recommends additional resources for learning regex, including books and online tools like regex libraries and testers for interactive practice.

24.7. Lab Answers
The chapter concludes with solutions to the lab exercises, guiding users on how to implement regex in practical situations and providing clarity on how to form valid patterns for their tasks.

Install Bookey App to unlock full text and audio

1000 + Book Summaries ,   80 + Topics

1000 + Book Summaries ,

80 + Topics

New titles added every week

Chapter 25 | Additional random tips, tricks, and techniques

Chapter 25: Additional Random Tips, Tricks, and Techniques

In this chapter, various tips and techniques to enhance PowerShell usage are discussed, helping users customize their environment, manipulate data, and improve efficiency.

25.1. Profiles, Prompts, and Colors: Customizing the Shell

25.1.1. PowerShell Profiles
PowerShell profiles allow users to customize their environment by setting up scripts that execute whenever a new shell session is started. Users can load modules, change directories, and define functions in these profiles. The order of profile execution is crucial, especially on systems that run both 32-bit and 64-bit versions of PowerShell.

25.1.2. Customizing the Prompt
Users can redefine the PowerShell prompt by creating a custom `Prompt` function that executes in profile scripts. For example, a new prompt can display the current time and computer name.

25.1.3. Tweaking Colors
PowerShell’s default colors can be modified for better readability. Users can change the colors for errors, warnings, and other types of messages either through the Properties interface or by executing commands in their profile scripts.

25.2. Operators: -as, -is, -replace, -join, -split, -in, -contains

These operators allow for more efficient manipulation of data types, strings, and collections.

25.2.1. -as and -is
The `-as` operator converts an object to a specified type, while `-is` checks an object’s type, returning a Boolean value.

25.2.2. -replace
The `-replace` operator finds and replaces occurrences of a string within another string.

25.2.3. -join and -split
The `-join` operator combines array elements into a single string, while `-split` breaks a string into an array based on a specified delimiter.

25.2.4. -contains and -in
The `-contains` operator checks for an object’s existence in a collection, while `-in` reverses operand order for similar checks.

25.3. String Manipulation
Strings in PowerShell are objects with various methods for manipulation, such as changing case or trimming whitespace. Common methods include `ToUpper()`, `ToLower()`, `Trim()`, and `IndexOf()`.

25.4. Date Manipulation
DateTime objects also include numerous methods for date manipulation. Users can perform calculations easily, such as adding days or converting to different formats.

25.5. Dealing with WMI Dates
WMI classes often store date information in complex formats. PowerShell provides `ConvertFromDateTime()` and `ConvertToDateTime()` methods to simplify handling these values.

25.6. Setting Default Parameter Values
In PowerShell v3, users can set default parameters for commands using the `$PSDefaultParameterValues` variable, enhancing command efficiency.

25.7. Playing with Script Blocks
Script blocks are versatile in PowerShell and can be defined and executed easily. They can be used with various cmdlets and functions to encapsulate reusable code.

25.8. More Tips, Tricks, and Techniques
Continual learning through various resources, including social media and forums, is emphasized. Users are encouraged to engage with the community for ongoing tips and improvements in PowerShell skills.

Chapter 26 | Using someone else’s script

Chapter 26: Using Someone Else’s Script

Overview
In this chapter, the importance of reusing and modifying PowerShell scripts from external sources is discussed. The readers are guided on how to understand and adapt someone else’s script effectively.

Understanding Scripts
The chapter introduces a script titled `New-WebProject.ps1`, designed to interface with Microsoft’s IIS cmdlets for server management. The script showcases advanced PowerShell features, which may not have been previously covered. The focus is on breaking down its components for better comprehension.

Key Components of the Script
1. Parameter Block: The script begins by defining mandatory parameters, `$Path` and `$Name`, which users need to provide.

2. Variable Initialization: The script sets up variables to establish paths for the system and the hosts file, vital for the script’s operations.

3. Functions:
— `New-LocalWebsite`: This primary function creates an IIS website and its associated application pool. It also checks for existing paths and manages the hosts file.
— `AddEntryToHosts`: This utility function appends a host entry to the hosts file.
— `HostsFileContainsEntry`: This function checks if the hosts file already has a specified entry.

Line-by-Line Examination
Readers are encouraged to analyze each line of the script:
— Identify and document variable values.
— Use PowerShell help commands to understand unfamiliar commands.
— Experiment with commands in a safe environment to see outcomes.

Lab Exercise
The chapter includes a lab to practice understanding a different script, `Get-LastOn.ps1`, which analyzes recent logon and logoff events from the event log. Users are tasked with predicting potential errors and adjustments needed for their environment.

Conclusion
The chapter emphasizes the need for thorough comprehension when using external scripts, encouraging exploration and testing to customize scripts for specific user scenarios. The process of understanding scripts aids in effective PowerShell scripting and troubleshooting.

Chapter 27 | Never the end

Chapter 27. Never the end

27.1. Ideas for further exploration
This chapter concludes the book while emphasizing that readers should continue their PowerShell learning journey. It highlights combining commands to automate processes and mentions a dedicated toolmaking book, «Learn PowerShell Toolmaking in a Month of Lunches.» Key toolmaking aspects include:
— PowerShell scripting language
— Functions and error handling
— Debugging and custom formatting views
— Using databases and workflows

27.2. “Now that I’ve read the book, where do I start?”
Post-reading, readers are encouraged to select repetitive tasks from their work to automate using PowerShell. Examples provided are:
— Scripting for password changes across multiple computers.
— Automating user provisioning in Exchange.
— Managing Exchange mailboxes and NTFS permissions.

27.3. Other resources you’ll grow to love
Several online resources are recommended for further learning:
— Powershell.org: forums, free ebooks, and webinars.
— YouTube channels for video tutorials.
— Blogs from PowerShell experts.
— Books for in-depth PowerShell knowledge, including «Learn PowerShell Toolmaking» and «PowerShell in Depth.»

This chapter encourages ongoing learning and engagement with the PowerShell community through various platforms and resources.

Install Bookey App to unlock full text and audio

In Windows, there’s a control panel, dialog box, console, or wizard to manage every component of a system. There are thousands of them—so many that it can be nearly impossible to keep track of all the locations and settings one needs to administer Windows effectively. PowerShell provides administrators with a single, unified command line from which they can control and automate every aspect of Windows.

Learn Windows PowerShell in a Month of Lunches is an innovative tutorial designed for busy administrators. Author Don Jones has taught thousands of administrators to use PowerShell, and now he brings his years of training techniques to a concise, easy-to-follow book. Just set aside one hour a day—lunchtime would be perfect—for an entire month, and readers will be automating administrative tasks faster than they ever thought possible.

Purchase of the print book comes with an offer of a free PDF, ePub, and Kindle eBook from Manning. Also available is all code from the book.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Install windows select the driver to install
  • Обновление системы безопасности ос windows 7 для систем на базе процессоров x64 kb4474419 201909
  • Scad office windows 10
  • При переустановке windows останутся ли файлы
  • Не удается открыть activation отказано в доступе в реестре windows 10