Searching...
English
EnglishEnglish
EspañolSpanish
简体中文Chinese
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
Bahasa IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Windows PowerShell Cookbook

Windows PowerShell Cookbook

The Complete Guide to Scripting Microsoft's Command Shell
by Lee Holmes 2007 1034 pages
3.84
100+ ratings
Listen
Try Full Access for 7 Days
Unlock listening & more!
Continue

Key Takeaways

1. Start with the familiar: PowerShell runs your existing tools.

What surprises most people when they first launch PowerShell is its similarity to the command prompt that has long existed as part of Windows.

Low barrier to entry. PowerShell is designed to be immediately productive for users familiar with command-line interfaces. You can run standard Windows executables like ipconfig.exe or notepad.exe just by typing their names, exactly as you would in cmd.exe. This means you don't have to abandon your existing command-line knowledge or tools to start using PowerShell.

Compatibility features. PowerShell includes features to ensure compatibility with traditional command-line tools and scripts. For executables with spaces in their path or name, use the invoke operator (&) and quotes, like & 'C:\Program Files\MyApp\app.exe'. To run scripts or executables located in the current directory, prefix the name with .\, such as .\myscript.ps1, mirroring behavior in Unix shells for added security.

Foundation for growth. While starting with familiar commands is easy, PowerShell's true power lies in its native cmdlets and scripting capabilities. This compatibility provides a comfortable starting point before you delve into more advanced, object-oriented features, allowing you to learn and adopt PowerShell incrementally.

2. Embrace the object pipeline: Data manipulation made easy.

PowerShell passes full-fidelity .NET objects between its commands.

Beyond text. Unlike traditional shells that pass data as plain text, PowerShell pipelines transmit rich, structured objects. This eliminates the need for fragile text parsing tools like awk or grep to extract meaningful information from command output.

Seamless data flow. The pipe operator (|) connects commands, directing the object output of one command directly into the object input of the next. This allows you to chain together simple commands to perform complex data manipulation tasks efficiently. For example, Get-Process | Where-Object { $_.WorkingSet -gt 100mb } | Sort-Object Name retrieves processes, filters them by memory usage, and sorts the resulting objects by name, all while preserving the full process object data.

Simplified scripting. Working directly with objects makes scripting significantly easier and more reliable. You can access object properties (like .Name or .Length) and call methods (like .Kill()) directly within the pipeline or in scripts, leveraging the full capabilities of the underlying data.

3. Master variables and objects: The core of PowerShell's power.

With those objects in hand, PowerShell makes it trivial for you to access properties of objects (such as their process name or memory usage) and to access functionality on these objects (such as stopping them, starting them, or waiting for them to exit).

Structured data. PowerShell is built upon the .NET Framework, meaning data is handled as structured objects rather than simple text strings. These objects encapsulate both information (properties) and actions (methods) related to the data they represent.

Accessing object members. You interact with objects using dot notation: $process.Id accesses the Id property of a process object, and $process.Kill() invokes the Kill method. This consistent syntax applies whether the object comes from a cmdlet, a .NET class, or another source.

Variables as containers. Variables, denoted by a dollar sign ($), store these objects for later use. You can assign the output of any command or pipeline to a variable, preserving the object's structure and functionality. PowerShell also provides automatic variables (like $error or $PSVersionTable) that offer insights into the current session and environment.

4. Control your scripts: Logic and loops for automation.

Together, looping and flow control statements add significant versatility to your PowerShell toolbox.

Adapting to data. Flow control statements allow your scripts to make decisions and execute different commands based on conditions. The if, elseif, and else statements provide conditional execution, while the switch statement offers a cleaner way to handle multiple comparison cases, even supporting pattern matching and file input.

Repeating actions. Looping statements enable your scripts to perform operations multiple times without repeating code. PowerShell offers several loop types:

  • for: Executes a block a specified number of times.
  • foreach: Iterates through each item in a collection.
  • while: Repeats a block as long as a condition is true.
  • do: Repeats a block until a condition is met (checked after the first execution).

Pipeline processing. The Foreach-Object cmdlet (% alias) is particularly useful for processing items as they arrive through the pipeline, offering efficiency for large datasets. Combining loops and conditionals allows you to write sophisticated scripts that can handle diverse scenarios and data inputs dynamically.

5. Handle text and strings: Powerful manipulation tools.

Since PowerShell lets you manage the majority of your system in its full fidelity (using cmdlets and objects), the text processing tools can once again focus primarily on actual text processing tasks.

String types. PowerShell supports different ways to define strings, including literal strings (single quotes '...') where content is taken exactly as written, and expanding strings (double quotes "...") where variables ($variable) and escape sequences (\n, \t) are interpreted. Here-strings (@"..."@) allow for multi-line text blocks while preserving formatting.

Operators for manipulation. Powerful operators are available for common text tasks. The -split operator breaks strings into arrays based on a delimiter or regular expression, while the -join operator combines array elements into a single string. The -replace operator performs text substitution, supporting both simple string replacement and complex regular expression patterns.

String methods. As .NET objects, strings also expose numerous methods for manipulation. Examples include .Length to get the string length, .Contains() to check for substrings, .IndexOf() to find substring positions, .ToUpper() and .ToLower() for case conversion, and .Trim() to remove leading/trailing whitespace.

6. Navigate and manage files: A consistent approach.

That complicated programmer-oriented script turns into a one-liner: Get-ChildItem -Recurse | Sort-Object -Descending Length | Select -First 10

Core file cmdlets. PowerShell provides a consistent set of cmdlets for interacting with the filesystem. Get-ChildItem (dir, ls) lists files and directories, Get-Item retrieves information about a specific item, New-Item creates files or directories, Remove-Item deletes them, and Move-Item and Rename-Item handle moving and renaming.

Powerful filtering. These cmdlets support robust filtering using wildcards (*, ?, []) directly in the -Path parameter or via the -Include and -Exclude parameters. For provider-specific filtering (like short filenames), the -Filter parameter is available. Additionally, the -Attributes parameter allows filtering by file attributes like ReadOnly, Hidden, or System.

Recursive operations. The -Recurse parameter enables operations on items within subdirectories, making it easy to perform tasks across an entire directory tree. Combined with the object pipeline, this allows for powerful, concise commands to find, filter, and act upon files based on their properties, as demonstrated by the quote example finding the largest files.

7. Administer the Registry: Treat it like a filesystem.

PowerShell tackles this problem by exposing the Windows Registry as a navigation provider: a data source that you navigate and manage in exactly the same way that you work with the filesystem.

Registry drives. PowerShell maps the main registry hives to drives, such as HKLM: for HKEY_LOCAL_MACHINE and HKCU: for HKEY_CURRENT_USER. This allows you to navigate the registry using familiar filesystem cmdlets like Set-Location (cd), Get-ChildItem (dir), Push-Location, and Pop-Location.

Key and value management. Registry keys are treated as items, and their values as properties of those items. You use Get-ItemProperty (gp) to view key values, Set-ItemProperty (sp) to modify them, New-ItemProperty to create new values, and Remove-ItemProperty to delete values.

Transactional safety. For related registry modifications, PowerShell supports transactions. Using Start-Transaction and applying changes with the -UseTransaction parameter ensures that either all changes are committed (Complete-Transaction) or none are (Undo-Transaction), preventing inconsistent states.

8. Work with Event Logs: Centralized system monitoring.

By building on PowerShell eventing, you can write scripts to quickly react to an ever-changing system.

Accessing logs. PowerShell provides Get-EventLog for accessing classic Windows event logs (Application, System, Security, etc.) and Get-WinEvent for accessing newer logs (Application and Services Logs) on Windows Vista and later. Get-EventLog -List or Get-WinEvent -ListLog * list available logs.

Filtering and analysis. Event log entries are returned as objects, enabling powerful filtering with Where-Object based on properties like Message, EntryType, EventID, or TimeGenerated. Get-WinEvent offers more efficient filtering options like -FilterHashtable and -FilterXPath for complex queries. Group-Object helps analyze event frequency.

Management tasks. Beyond retrieval, PowerShell cmdlets allow for comprehensive event log management. Write-EventLog adds custom entries, Clear-EventLog empties a log, and Limit-EventLog configures log size and retention policies. You can also export logs using wevtutil.exe or Export-CliXml for backup or offline analysis.

9. Manage Processes and Services: Control running applications.

Since PowerShell’s Get-Process cmdlet returns information as highly structured .NET objects, fragile text parsing becomes a thing of the past: Get-Process | Where-Object { $_.WorkingSet -gt 100mb } | Stop-Process -WhatIf

Process control. The Get-Process (gps) cmdlet retrieves running processes as rich objects, providing access to properties like Name, Id, WorkingSet, and StartTime. This object-based output allows for precise filtering and sorting without text parsing. Stop-Process (kill) terminates processes, and Wait-Process pauses script execution until a process exits.

Service management. Similarly, Get-Service retrieves system services as objects with properties like Name, DisplayName, and Status. You can filter services (e.g., Get-Service | Where-Object {$_.Status -eq 'Running'}) and manage their lifecycle.

Service actions. Dedicated cmdlets perform service actions: `
[ERROR: Incomplete response]

Last updated:

Review Summary

3.84 out of 5
Average of 100+ ratings from Goodreads and Amazon.

Readers find Windows PowerShell Cookbook to be a comprehensive reference for experienced developers. However, beginners may find it overwhelming due to its size and depth. One reviewer describes it as "drinking from a fire hose" and suggests it's better suited for those already familiar with PowerShell basics. Another notes it's helpful as a physical reference while learning, but not ideal for casual reading. The book's extensive content is both praised for its thoroughness and criticized for being potentially too much for newcomers to digest easily.

Your rating:
4.2
3 ratings

About the Author

Lee Holmes is a respected author and expert in the field of Windows PowerShell. With extensive experience in software development and automation, Holmes has contributed significantly to the PowerShell community. He is known for his clear and practical approach to explaining complex technical concepts. Holmes has worked at Microsoft, where he played a key role in developing PowerShell. His expertise extends beyond writing, as he is also recognized for his contributions to various PowerShell-related projects and tools. Holmes' work has helped many IT professionals and developers harness the power of PowerShell for system administration and automation tasks.

Download PDF

To save this Windows PowerShell Cookbook summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.30 MB     Pages: 13

Download EPUB

To read this Windows PowerShell Cookbook summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 2.97 MB     Pages: 11
Listen to Summary
0:00
-0:00
1x
Dan
Andrew
Michelle
Lauren
Select Speed
1.0×
+
200 words per minute
Home
Library
Get App
Create a free account to unlock:
Requests: Request new book summaries
Bookmarks: Save your favorite books
History: Revisit books later
Recommendations: Personalized for you
Ratings: Rate books & see your ratings
100,000+ readers
Try Full Access for 7 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
All summaries are free to read in 40 languages
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
❤️ Unlimited Bookmarks
Free users are limited to 10
📜 Unlimited History
Free users are limited to 10
📥 Unlimited Downloads
Free users are limited to 1
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 73,530 books. That's 12,000+ hours of audio!
Day 4: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 7: Your subscription begins
You'll be charged on May 22,
cancel anytime before.
Consume 2.8x More Books
2.8x more books Listening Reading
Our users love us
100,000+ readers
"...I can 10x the number of books I can read..."
"...exceptionally accurate, engaging, and beautifully presented..."
"...better than any amazon review when I'm making a book-buying decision..."
Save 62%
Yearly
$119.88 $44.99/year
$3.75/mo
Monthly
$9.99/mo
Try Free & Unlock
7 days free, then $44.99/year. Cancel anytime.
Scanner
Find a barcode to scan

Settings
General
Widget
Loading...