OReilly - Windows PowerShell Cookbook 3rd Edition - Lee Holmes - ISBN 1449320686
Link 1: Index of /computer/Windows
Link 2: Windows PowerShell Cookbook [pdf]
Supply Default Values for Parameters
PowerShell version 3 introduces the PSDefaultParameterValues preference variable. This preference variable is a hashtable.
Keys in the PSDefaultParameterValues hashtable must match the pattern cmdlet:parameter - that is, a cmdlet name and parameter name, separated by a colon. For example, the Send-MailMessage cmdlet looks for the $PSEmailServer variable if you do not supply a value for its -SmtpServer parameter.
[Console]::Beep(100,100) - Console.Beep Method
Learn Aliases for Common Parameters - Get-ParameterAlias.ps1 - Tokenizer API
If you want to see the aliases for a specific command, you can access its Parameters collection
(Get-Command New-TimeSpan).Parameters.Values | Select Name,Aliases
Search (formatted) command output for a pattern
Get-Service | Out-String -Stream | Select-String <search text> OR Get-Service | oss | sls <text>
Interactively View and Explore Objects - Show-Object - Abstract Syntax Tree (AST)
Automatic Variables - $pid
PS > $ps = { Get-Process -ID $pid }.Ast
PS > Show-Object.ps1 $ps
Redirecting output of a command into a file - A16 Capturing output
Get-Content .\infile.txt | Out-File -Encoding ascii -Width 100 -Append outfile.txt
Record a Transcript of Your Shell Session - places file in My Documents
Start-Transcript .... Stop-Transcript
When you install a module on your own system, the most common place to put it is in the WindowsPowerShell\Modules directory in your My Documents directory. To have PowerShell look in another directory for modules, add it to your personal PSModule Path environment variable.
Pipeline Examples - In the script block, the $_ (or $PSItem) variable represents the current input object.
Group and Pivot Data by Name (91) - $processes = Get-Process | Group-Object -AsHash Id
Foreach-Object - In addition to the script block supported by the Foreach-Object cmdlet to process each element of the pipeline, it also supports script blocks to be executed at the beginning and end of the pipeline.
$myArray = 1,2,3,4,5
$myArray | Foreach-Object -Begin {$sum = 0 } -Process { $sum += $_ } -End { $sum }
$myArray | Foreach-Object { $sum = 0 } { $sum += $_ } { $sum }
Output formatting - 4 cmdlets - Format-Table, Format-List, Format-Wide and Format-Custom
By default, PowerShell takes the list of properties to display from the *.format.ps1xml files in PowerShell’s installation directory. In many situations, you’ll only get a small set of the properties.
PowerShell automatically defines several variables that represent things such as the location of your profile file, the process ID of
PowerShell, and more. For a full list of these automatic variables, type Get-Help about_automatic_variables.
$fields = "Name",@{Label = "WS (MB)"; Expression = {$_.WS / 1mb}; Align = "Right"}
Get-Process | Format-Table $fields -Auto
ls | select Name,@{Name="Size (MB)"; Expression={"{0,8:0.00}" -f ($_.Length / 1MB)}}
Access Environment Variables - list all - Get-ChildItem env:
Get-ChildItem env:username OR Get-ChildItem Environment::username
Control Access and Scope of Variables - Get-Help About_Scope
Work with .NET Objects - Classes contain methods (which let you perform operations) and properties (which let
you access information)
static method - [ClassName]::MethodName(parameter list) or [System.Diagnostics.Process]::GetProcessById(0)
[System.DateTime]::Now
instance method - $objectReference.MethodName(parameter list) or $process.WaitForExit()
$today = Get-Date -> $today.DayOfWeek
Selected .NET Classes and their uses (943) or .NET API Browser
Scope of Variables (128) - common = Global, Script & Local; also see Variables (864)
Create an Instance of a .NET Object (138)
$generator = New-Object System.Random; $generator.NextDouble()
OR (New-Object Net.WebClient).DownloadString("http://live.com")
Add-Type -Assembly System.Windows.Forms
$image = New-Object System.Drawing.Bitmap source.gif
$image.Save("source_converted.jpg", "JPEG")
Create Instances of Generic Objects
$coll = New-Object System.Collections.ObjectModel.Collection[Int]
$coll.Add(15) << with only integer number or multiparameter below
$map = New-Object "System.Collections.Generic.Dictionary[String,Int]"
$map.Add("Test", 15)
Reduce Typing for Long Class Names - static methods, multiple objects & statis methods with mupltile types
$math = [System.Math]; $math::Min(1,10)
$namespace = "System.Collections.{0}"; $arrayList = New-Object ($namespace -f "ArrayList")
$namespace = "System.Diagnostics.{0}"; ([Type] ($namespace -f "EventLog"))::GetEventLogs()
Use a COM Object - Selected COM Objects and Their Uses (959)
$sapi = New-Object -Com Sapi.SpVoice
$sapi.Speak("Hello World")
Create and Initialize Custom Objects, Add Custom Methods and Properties to Types,
Define Custom Formatting for a Type, Using Conditional Statements,
Conditional Statements with Switches (Operating System SKU),
Operations with Loops, Looping Statements, Running a loop at a constant speed
Strings - Literal ($str='Hello') and Expanding strings ($str="Hello") or single and double quotes
Place Special Characters in a String, Insert Dynamic Information in a String,
Prevent a String from Including Dynamic Information, Place Formatted Information in a String,
Search a String for Text or a Pattern, Replace Text in a String,
Split a String on Text or a Pattern, Combine (join) Strings into a Larger String,
Convert a String to Uppercase or Lowercase, Trim a String,
Format a Date for Output, Convert Text Streams to Objects,
Generate Large Reports and Text Streams, Generate Source Code and Other Repetitive Text
PowerShell’s formatting - Simple Operators, Detailed list of the formatting rules (933)
String.Format Method (MS docs), Standard Numeric Format Strings (MS Docs)
Search a string for Text or a Pattern
- like operator > "Hello World" -like "*llo W*" >> True
- match operator > "Hello World" -match '.*l[l-z]o W.*$' >> True
- Contains() method > "Hello World".Contains("World") >> True
- IndexOf() method to determine location of 1 string within another > "Hello World".IndexOf("World") >> 6
A common use of regular expressions is to search for a string that spans multiple lines. By default, regular expressions do not search across lines, but you can use the singleline (?s) option to instruct them to do so:
PS > "Hello `n World" -match "Hello.*World" >> False
PS > "Hello `n World" -match "(?s)Hello.*World" >> True
Regular Expression Reference
Replace string & Split string - see Split a String on Text or a Pattern
Calculations and Math
Perform Simple Arithmetic, Perform Complex Arithmetic, Measure Statistical Properties of a List
Work with Numbers as Binary, Simplify Math with Administrative Constants, Convert Numbers Between Bases
Lists, Arrays, and Hashtables - Arrays and Lists, Hashtables (Associative Arrays)
Create an Array or List of Items, Create a Jagged or Multidimensional Array, Access Elements of an Array
Visit Each Element of an Array, Sort an Array or List of Items, Determine Whether an Array Contains an Item
Combine Two Arrays, Find Items in an Array That Match a Value, Compare Two Lists
Remove Elements from an Array, Find Items in an Array Greater or Less Than a Value, Use the ArrayList Class for Advanced Array Tasks
Create a Hashtable or Associative Array, Sort a Hashtable by Key or Value
Utility Tasks
Get the System Date and Time, Measure the Duration of a Command, Read and Write from the Windows Clipboard
Generate a Random Number or Object, Program: Search the Windows Start Menu, Program: Show Colorized Script Content
---------------------------------------------------------------------
Common Tasks
Simple Files
Get the Content of a File, Search a File for Text or a Pattern, Parse and Manage Text-Based Logfiles
Parse and Manage Binary Files, Create a Temporary File, Search and Replace Text in a File
.
Link 1: Index of /computer/Windows
Link 2: Windows PowerShell Cookbook [pdf]
Supply Default Values for Parameters
PowerShell version 3 introduces the PSDefaultParameterValues preference variable. This preference variable is a hashtable.
Keys in the PSDefaultParameterValues hashtable must match the pattern cmdlet:parameter - that is, a cmdlet name and parameter name, separated by a colon. For example, the Send-MailMessage cmdlet looks for the $PSEmailServer variable if you do not supply a value for its -SmtpServer parameter.
[Console]::Beep(100,100) - Console.Beep Method
Learn Aliases for Common Parameters - Get-ParameterAlias.ps1 - Tokenizer API
If you want to see the aliases for a specific command, you can access its Parameters collection
(Get-Command New-TimeSpan).Parameters.Values | Select Name,Aliases
Search (formatted) command output for a pattern
Get-Service | Out-String -Stream | Select-String <search text> OR Get-Service | oss | sls <text>
Interactively View and Explore Objects - Show-Object - Abstract Syntax Tree (AST)
Automatic Variables - $pid
PS > $ps = { Get-Process -ID $pid }.Ast
PS > Show-Object.ps1 $ps
Redirecting output of a command into a file - A16 Capturing output
Get-Content .\infile.txt | Out-File -Encoding ascii -Width 100 -Append outfile.txt
Record a Transcript of Your Shell Session - places file in My Documents
Start-Transcript .... Stop-Transcript
When you install a module on your own system, the most common place to put it is in the WindowsPowerShell\Modules directory in your My Documents directory. To have PowerShell look in another directory for modules, add it to your personal PSModule Path environment variable.
Pipeline Examples - In the script block, the $_ (or $PSItem) variable represents the current input object.
Group and Pivot Data by Name (91) - $processes = Get-Process | Group-Object -AsHash Id
Foreach-Object - In addition to the script block supported by the Foreach-Object cmdlet to process each element of the pipeline, it also supports script blocks to be executed at the beginning and end of the pipeline.
$myArray = 1,2,3,4,5
$myArray | Foreach-Object -Begin {$sum = 0 } -Process { $sum += $_ } -End { $sum }
$myArray | Foreach-Object { $sum = 0 } { $sum += $_ } { $sum }
Output formatting - 4 cmdlets - Format-Table, Format-List, Format-Wide and Format-Custom
By default, PowerShell takes the list of properties to display from the *.format.ps1xml files in PowerShell’s installation directory. In many situations, you’ll only get a small set of the properties.
PowerShell automatically defines several variables that represent things such as the location of your profile file, the process ID of
PowerShell, and more. For a full list of these automatic variables, type Get-Help about_automatic_variables.
$fields = "Name",@{Label = "WS (MB)"; Expression = {$_.WS / 1mb}; Align = "Right"}
Get-Process | Format-Table $fields -Auto
ls | select Name,@{Name="Size (MB)"; Expression={"{0,8:0.00}" -f ($_.Length / 1MB)}}
Access Environment Variables - list all - Get-ChildItem env:
Get-ChildItem env:username OR Get-ChildItem Environment::username
Control Access and Scope of Variables - Get-Help About_Scope
Work with .NET Objects - Classes contain methods (which let you perform operations) and properties (which let
you access information)
static method - [ClassName]::MethodName(parameter list) or [System.Diagnostics.Process]::GetProcessById(0)
[System.DateTime]::Now
instance method - $objectReference.MethodName(parameter list) or $process.WaitForExit()
$today = Get-Date -> $today.DayOfWeek
Selected .NET Classes and their uses (943) or .NET API Browser
Scope of Variables (128) - common = Global, Script & Local; also see Variables (864)
Create an Instance of a .NET Object (138)
$generator = New-Object System.Random; $generator.NextDouble()
OR (New-Object Net.WebClient).DownloadString("http://live.com")
Add-Type -Assembly System.Windows.Forms
$image = New-Object System.Drawing.Bitmap source.gif
$image.Save("source_converted.jpg", "JPEG")
Create Instances of Generic Objects
$coll = New-Object System.Collections.ObjectModel.Collection[Int]
$coll.Add(15) << with only integer number or multiparameter below
$map = New-Object "System.Collections.Generic.Dictionary[String,Int]"
$map.Add("Test", 15)
Reduce Typing for Long Class Names - static methods, multiple objects & statis methods with mupltile types
$math = [System.Math]; $math::Min(1,10)
$namespace = "System.Collections.{0}"; $arrayList = New-Object ($namespace -f "ArrayList")
$namespace = "System.Diagnostics.{0}"; ([Type] ($namespace -f "EventLog"))::GetEventLogs()
Use a COM Object - Selected COM Objects and Their Uses (959)
$sapi = New-Object -Com Sapi.SpVoice
$sapi.Speak("Hello World")
Create and Initialize Custom Objects, Add Custom Methods and Properties to Types,
Define Custom Formatting for a Type, Using Conditional Statements,
Conditional Statements with Switches (Operating System SKU),
Operations with Loops, Looping Statements, Running a loop at a constant speed
Strings - Literal ($str='Hello') and Expanding strings ($str="Hello") or single and double quotes
Place Special Characters in a String, Insert Dynamic Information in a String,
Prevent a String from Including Dynamic Information, Place Formatted Information in a String,
Search a String for Text or a Pattern, Replace Text in a String,
Split a String on Text or a Pattern, Combine (join) Strings into a Larger String,
Convert a String to Uppercase or Lowercase, Trim a String,
Format a Date for Output, Convert Text Streams to Objects,
Generate Large Reports and Text Streams, Generate Source Code and Other Repetitive Text
PowerShell’s formatting - Simple Operators, Detailed list of the formatting rules (933)
String.Format Method (MS docs), Standard Numeric Format Strings (MS Docs)
Search a string for Text or a Pattern
- like operator > "Hello World" -like "*llo W*" >> True
- match operator > "Hello World" -match '.*l[l-z]o W.*$' >> True
- Contains() method > "Hello World".Contains("World") >> True
- IndexOf() method to determine location of 1 string within another > "Hello World".IndexOf("World") >> 6
A common use of regular expressions is to search for a string that spans multiple lines. By default, regular expressions do not search across lines, but you can use the singleline (?s) option to instruct them to do so:
PS > "Hello `n World" -match "Hello.*World" >> False
PS > "Hello `n World" -match "(?s)Hello.*World" >> True
Regular Expression Reference
Replace string & Split string - see Split a String on Text or a Pattern
Calculations and Math
Perform Simple Arithmetic, Perform Complex Arithmetic, Measure Statistical Properties of a List
Work with Numbers as Binary, Simplify Math with Administrative Constants, Convert Numbers Between Bases
Lists, Arrays, and Hashtables - Arrays and Lists, Hashtables (Associative Arrays)
Create an Array or List of Items, Create a Jagged or Multidimensional Array, Access Elements of an Array
Visit Each Element of an Array, Sort an Array or List of Items, Determine Whether an Array Contains an Item
Combine Two Arrays, Find Items in an Array That Match a Value, Compare Two Lists
Remove Elements from an Array, Find Items in an Array Greater or Less Than a Value, Use the ArrayList Class for Advanced Array Tasks
Create a Hashtable or Associative Array, Sort a Hashtable by Key or Value
Utility Tasks
Get the System Date and Time, Measure the Duration of a Command, Read and Write from the Windows Clipboard
Generate a Random Number or Object, Program: Search the Windows Start Menu, Program: Show Colorized Script Content
---------------------------------------------------------------------
Common Tasks
Simple Files
Get the Content of a File, Search a File for Text or a Pattern, Parse and Manage Text-Based Logfiles
Parse and Manage Binary Files, Create a Temporary File, Search and Replace Text in a File
.