By Lee Holmes
Book Price: $49.99 USD
£30.99 GBP
PDF Price: $39.99
Cover | Table of Contents | Colophon
Program.exe arguments ScriptName.ps1 arguments BatchFile.cmd arguments
& 'C:\Program Files\Program\Program.exe' arguments
.\Program.exe arguments
& '.\Program With Spaces.exe' arguments
Program.exe arguments ScriptName.ps1 arguments BatchFile.cmd arguments
& 'C:\Program Files\Program\Program.exe' arguments
.\Program.exe arguments
& '.\Program With Spaces.exe' arguments
"C:\Program Files\Program\Program.exe"
PS >1 + 1 2 PS >26 * 1.15 29.9 PS >"Hello" + " World" Hello World PS >"Hello World" Hello World PS >"C:\Program Files\Program\Program.exe" C:\Program Files\Program\Program.exe PS >
PS >Get-Process Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 133 5 11760 7668 46 1112 audiodg 184 5 33248 508 93 1692 avgamsvr 143 7 31852 984 97 1788 avgemc
Get-Process command is an example of a native PowerShell command, called a cmdlet. As compared to traditional commands, cmdlets provide significant benefits to both administrators and developers:Get-Process cmdlet generates rich object-based output, you can use its output for many process-related tasks.Get-Process cmdlet is just one of the many that PowerShell supports. See , "Find a Command to Accomplish a Task" to learn techniques for finding additional commands that PowerShell supports.$profile variable.New-Item -type file -force $profile
notepad $profile
Get-ChildItem $profile
Prompt that returns a string. PowerShell displays the output of this function as your command-line prompt.
function Prompt
{
"PS [$env:COMPUTERNAME] >"
}
PS [LEE-DESK]>Set-Alias new New-Object Set-Alias iexplore 'C:\Program Files\Internet Explorer\iexplore.exe'
. $profile
Prompt function.PromptGet-Command cmdlet to search for and investigate commands.
Get-Command CommandName
Get-Command to the Format-List cmdlet:
Get-Command CommandName | Format-List
Get-Command *text*
Get verb, supply Get to the -Verb parameter:
Get-Command -Verb Get
Service to the -Noun parameter:
Get-Command -Noun Service
Get-Process, Get-EventLog, and Set-Location. The verbs come from a relatively small set of standard verbs (as listed in , Standard PowerShell Verbs), and describe what action the cmdlet takes. The nouns are specific to the cmdlet and describe what the cmdlet acts on.Start.A good guess would be to first try Start-Service (which in this case would be correct), but typing Get-Command -Verb Start would also be an effective way to see what things you can start. Going the other way, you can see what actions are supported on services by typing Get-Command -Noun Service.Get-Command cmdlet is one of the three commands you will use most commonly as you explore Windows PowerShell. The other two commands are Get-Help and Get-Member.Get-Help. It supports several different views of the help information, depending on your needs.Get-Help cmdlet. This primarily includes its synopsis, syntax, and detailed description:
Get-Help CommandName
CommandName -?
Detailed flag to the Get-Help cmdlet. In addition to the summary view, this also includes its parameter descriptions and examples:
Get-Help CommandName -Detailed
Full flag to the Get-Help cmdlet. In addition to the detailed view, this also includes its full parameter descriptions and additional notes:
Get-Help CommandName -Full
Examples flag to the Get-Help cmdlet:
Get-Help CommandName -Examples
Get-Help cmdlet is the primary way to interact with the help system in PowerShell. Like the Get-Command cmdlet, the Get-Help cmdlet supports wildcards. If you want to list all commands that match a certain pattern (for example, *process*), you can simply type Get-Help *process*.Get-Help * | Select-Object Name,Synopsis | Format-Table -Auto
Get-Help cmdlet is one of the three commands you will use most commonly as you explore Windows PowerShell. The other two commands are Get-Command and Get-Member.Get-Help cmdlet, type Get-Help Get-Help.Get-Command and Get-Help cmdlets let you search for command names that match a given pattern. However, when you don't know exactly what portions of a command name you are looking for, you will more often have success searching through the help content for an answer. On Unix systems, this command is called Apropos. Similar functionality does not exist as part of the PowerShell's help facilities, however.Search-Help script (given in ). The search string can be either simple text or a regular expression. The script then displays the name and synopsis of all help topics that match. To see the help content for that topic, use the Get-Help cmdlet.
##############################################################################
##
## Search-Help.ps1
##
## Search the PowerShell help documentation for a given keyword or regular
## expression.
##
## Example:
## Search-Help hashtable
## Search-Help "(datetime|ticks)"
##############################################################################
param($pattern = $(throw "Please specify content to search for"))
$helpNames = $(Get-Help * | Where-Object { $_.Category -ne "Alias" })
foreach($helpTopic in $helpNames)
{
$content = Get-Help -Full $helpTopic.Name | Out-String
if($content -match $pattern)
{
$helpTopic | Select-Object Name,Synopsis
}
}
PowerShell "& 'full path to script' arguments"
PowerShell "& 'c:\shared scripts\Get-Report.ps1' Hello World"
EncodedCommand parameter: a Base64 encoded representation of the Unicode string you want to run. demonstrates how to convert a string containing PowerShell commands to a Base64 encoded form.
$commands = '1..10 | % { "PowerShell Rocks" }'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($commands)
$encodedString = [Convert]::ToBase64String($bytes)
EncodedCommand parameter, as shown in .Microsoft Windows [Version 6.0.6000] Copyright (c) 2006 Microsoft Corporation. All rights reserved. C:\Users\Lee>PowerShell -EncodedCommand MQAuAC4AMQAwACAAfAAgACUAIAB7ACAAIgBQAG8A↵ dwBlAHIAUwBoAGUAbABsACAAUgBvAGMAawBzACIAIAB9AA== PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks PowerShell Rocks
cmd.exe /c MyScript.cmd).Get-Content, Foreach-Object, Set-Content, and Remove-Item. This makes the script readable and is ideal for scripts that somebody else will read. It is by no means required, though. For quick scripts and interactive use, shorter aliases (such as gc, %, sc, and ri) can make you more productive.
##############################################################################
##
## Invoke-CmdScript.ps1
##
## Invoke the specified batch file (and parameters), but also propagate any
## environment variable changes back to the PowerShell environment that
## called it.
##
## i.e., for an already existing 'foo-that-sets-the-FOO-env-variable.cmd':
##
## PS > type foo-that-sets-the-FOO-env-variable.cmd
## @set FOO=%*
## echo FOO set to %FOO%.
##
## PS > $env:FOO
##
## PS > Invoke-CmdScript "foo-that-sets-the-FOO-env-variable.cmd" Test
##
## C:\Temp>echo FOO set to Test.
## FOO set to Test.
##
## PS > $env:FOO
## Test
##
##############################################################################
param([string] $script, [string] $parameters)
$tempFile = [IO.Path]::GetTempFileName()
## Store the output of cmd.exe. We also ask cmd.exe to output
## the environment table after the batch file completes
cmd /c " '"$script'" $parameters && set > '"$tempFile'" "
## Go through the environment variables in the temp file.
## For each of them, set the variable in our local environment.
Get-Content $tempFile | Foreach-Object {
if($_ -match "^(.*?)=(.*)$")
{
Set-Content "env:\$($matches[1])" $matches[2]
}
}
Remove-Item $tempFile
Get-Date.Get-Date command generates rich object-based output, so you can use its result for many date-related tasks. For example, to determine the current day of the week:PS >$date = Get-Date PS >$date.DayOfWeek Sunday
Get-Date cmdlet, type Get-Help Get-Date.$lastExitCode variable and the $? variable.$lastExitCode$? (pronounced "dollar hook")$lastExitCode PowerShell variable is similar to the %errorlevel% variable in DOS. It holds the exit code of the last application to exit. This lets you continue to interact with traditional executables (such as ping, findstr, and choice) that use exit codes as a primary communication mechanism. PowerShell also extends the meaning of this variable to include the exit codes of scripts, which can set their status using the exit statement. demonstrates this interaction.
PS >ping localhost
Pinging MyComputer [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milliseconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
PS >$?
True
PS >$lastExitCode
0
PS >ping missing-host
Ping request could not find host missing-host. Please check the name and try again.
PS >$?
False
PS >$lastExitCode
1
$? variable describes the exit status of the last application in a more general manner. PowerShell sets this variable to False on error conditions such as when:$? variable to True.Measure-Command cmdlet:
PS >Measure-Command { Start-Sleep -Milliseconds 337 }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 339
Ticks : 3392297
TotalDays : 3.92626967592593E-06
TotalHours : 9.42304722222222E-05
TotalMinutes : 0.00565382833333333
TotalSeconds : 0.3392297
TotalMilliseconds : 339.2297
Measure-Command cmdlet makes this easy to do. Because the command generates rich object-based output, you can use its output for many date-related tasks. See , "Work with .NET Objects," for more information.Measure-Command cmdlet, type Get-Help Measure-Command.Push-Location Set-Location HKCU:\Console New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe' Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe' New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401 New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee New-ItemProperty . FaceName -type STRING -value "Lucida Console" New-ItemProperty . FontFamily -type DWORD -value 0x00000036 New-ItemProperty . FontSize -type DWORD -value 0x000c0000 New-ItemProperty . FontWeight -type DWORD -value 0x00000190 New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000 New-ItemProperty . QuickEdit -type DWORD -value 0x00000001 New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078 New-ItemProperty . WindowSize -type DWORD -value 0x00320078 Pop-Location
Hotkey | Meaning |
|---|---|
Up arrow | Scan backward through your command history. |
Down arrow | Scan forward through your command history. |
PgUp | Display the first command in your command history. |
PgDown | Display the last command in your command history. |
Left arrow | Move cursor one character to the left on your command line. |
Right arrow | Move cursor one character to the right on your command line. |
Home | Move the cursor to the beginning of the command line. |
End | Move the cursor to the end of the command line. |
Control + Left arrow | Move the cursor one word to the left on your command line. |
Get-ChildItem) are cumbersome and slow to type. Although aliases are much more efficient, it takes awhile to discover them. To learn aliases more easily, you can modify your prompt to remind you of the shorter version of any aliased commands that you use.Get-AliasSuggestion.ps1, shown in , to your tools directory or other directory.
##############################################################################
##
## Get-AliasSuggestion.ps1
##
## Get an alias suggestion from the full text of the last command
##
## ie:
##
## PS > Get-AliasSuggestion Remove-ItemProperty
## Suggestion: An alias for Remove-ItemProperty is rp
##
##############################################################################
param($lastCommand)
$helpMatches = @()
## Get the alias suggestions
foreach($alias in Get-Alias)
{
if($lastCommand -match ("\b" +
[System.Text.RegularExpressions.Regex]::Escape($alias.Definition) + "\b"))
{
$helpMatches += "Suggestion: An alias for $($alias.Definition) is $($alias.Name)"
}
}
$helpMatches
Prompt function in your profile. If you do not yet have a Prompt function, see , "Customize Your Shell, Profile, and Prompt" to learn how to add one. If you already have a prompt function, you only need to add the content from inside the prompt function of .
function Prompt
{
## Get the last item from the history
$historyItem = Get-History -Count 1
## If there were any history items
if($historyItem)
{
## Get the training suggestion for that item
$suggestions = @(Get-AliasSuggestion $historyItem.CommandLine)
## If there were any suggestions
if($suggestions)
{
## For each suggestion, write it to the screen
foreach($aliasSuggestion in $suggestions)
{
Write-Host "$aliasSuggestion"
}
Write-Host ""
}
}
## Rest of prompt goes here
"PS [$env:COMPUTERNAME] >"
}
Get-History cmdlet:Get-History
Invoke-History cmdlet:
Invoke-History Id
$MaximumHistoryCount variable:
$MaximumHistoryCount = Count
Get-History to the Export-CliXml cmdlet:
Get-History | Export-CliXml Filename
Import-CliXml Filename | Add-History
Get-History cmdlet produces rich objects that represent information about items in your history. Each object contains that item's ID, command line, start of execution time, and end of execution time.Get-History), you can pass it to Invoke-History to execute that command again. The example prompt function shown in , "Customize Your Shell, Profile, and Prompt" makes working with prior history items easy—as the prompt for each command includes the history ID that will represent it.Get-History cmdlet differ from the IDs given by the Windows console common history hotkeys (such as F7), because their history management techniques differ.$MaximumHistoryCount variable to the size you desire. To make this change permanent, set the variable in your PowerShell profile script. To clear your history, either restart the shell, or temporarily set the Out-File cmdlet or one of the redirection operators.Out-File:Get-ChildItem | Out-File unicodeFile.txt Get-Content filename.cs | Out-File -Encoding ASCII file.txt Get-ChildItem | Out-File-Width 120 unicodeFile.cs
Get-ChildItem > files.txt Get-ChildItem 2> errors.txt
Out-File cmdlet and redirection operators share a lot in common—and for the most part, you can use either. The redirection operators are unique because they give the greatest amount of control over redirecting individual streams. The Out-File cmdlet is unique primarily because it lets you easily configure the formatting width and encoding.Width parameter on the Out-File cmdlet.Encoding parameter on the Out-File cmdlet.Out-File cmdlet, type Get-Help Out-File. For a full list of supported redirection operators, see "Capturing Output" in .Append parameter of the Out-File cmdlet, or one of the appending redirection operators as described in "Capturing Output" in . Both support options to append text to the end of a file.Out-File:
Get-ChildItem | Out-File -Append files.txt
Get-ChildItem >> files.txt
Out-File cmdlet and redirection operators share a lot in common—and for the most part, you can use either. See the discussion in , "Store the Output of a Command into a File" for a more detailed comparison of the two approaches, including reasons that you would pick one over the other.Start-Transcript Path. Path is optional and defaults to a filename based on the current system time. By default, PowerShell places this file in the My Documents directory. To stop recording the transcript of your shell system, run the command Stop-Transcript.Get-History cmdlet is helpful, it does not record the output produced during your PowerShell session. To accomplish that, use the Start-Transcript cmdlet. In addition to the Path parameter described previously, the Start-Transcript cmdlet also supports parameters that let you control how PowerShell interacts with the output file.Format-List cmdlet. For example, to display an error in list format, type the commands:$currentError = $error[0] $currentError | Format-List -Force
Format-List cmdlet is one of the three PowerShell formatting cmdlets. These cmdlets include Format-Table, Format-List, and Format-Wide. The Format-List cmdlet takes input and displays information about that input as a list. By default, PowerShell takes the list of properties to display from the *.format.ps1xml files in PowerShell's installation directory. To display all properties of the item, type Format-List *. Sometimes, you might type Format-List * but still not get a list of the item's properties. This happens when the item is defined in the *.format.ps1xml files, but does not define anything to be displayed for the list command. In that case, type Format-List-Force. Format-Table cmdlet. This is the default type of formatting for sets of items in PowerShell and provides several useful features.Get-Process cmdlet) to the Format-Table cmdlet:Get-Process | Format-Table
Format-Table cmdlet:Get-Process | Format-Table Name,WS
Auto flag to the Format-Table cmdlet. PowerShell defines "WS" as an alias of the WorkingSet for processes:Get-Process | Format-Table Name,WS -Auto
Format-Table cmdlet:
$fields = "Name",@{Label = "WS (MB)"; Expression = {$_.WS / 1mb}; Align = "Right"}
Get-Process | Format-Table $fields -Auto
Format-Table cmdlet is one of the three PowerShell formatting cmdlets. These cmdlets include Format-Table, Format-List, and Format-Wide. The Format-Table cmdlet takes input and displays information about that input as a table. By default, PowerShell takes the list of properties to display from the *.format.ps1xml files in PowerShell's installation directory. You can display all properties of the items if you type Format-Table *, although this is rarely a useful view.Format-Table is a helpful way to automatically format the table to use screen space as efficiently as possible. It does come at a cost, however. To figure out the best table layout, PowerShell needs to examine each item in the incoming set of items. For small sets of items, this doesn't make much difference, but for large sets (such as a recursive directory listing) it does. Without the -$MaximumErrorCount) that have occurred in this session, access the $error array:$error
$error array:$error[0]
Format-List cmdlet with the -Force parameter:$currentError = $error[0] $currentError | Format-List -Force
InvocationInfo property:$currentError = $error[0] $currentError.InvocationInfo
$errorView variable to "CategoryView":$errorView = "CategoryView"
Clear() method on the $error variable:$error.Clear()
Copy-Item cmdlet. If it fails to copy a file from one location to another, it can still proceed with the rest of the files specified.Copy-Item cmdlet when you specify invalid command-line parameters.$debugPreference = "Continue" Start-DebugCommand
Verbose parameter:Copy-Item c:\temp\*.txt c:\temp\backup\ -Verbose
$progressPreference = "SilentlyContinue" Get-Progress.ps1
Write-Debug cmdlet to produce this type of output in a script or the WriteDebug() method to produce this type of output in a cmdlet. PowerShell displays this output in yellow, unless you customize it through the $host.PrivateData.Debug* color configuration variables.Write-Verbose cmdlet to produce this type of output in a script or the WriteVerbose() method to produce this type of output in a cmdlet. PowerShell displays this output in yellow, unless you customize it through the $host.PrivateData.Verbose* color configuration variables.Write-Progress cmdlet to produce this type of output in a script or the WriteProgress() method to produce this type of output in a cmdlet. PowerShell displays this output in yellow, unless you customize it through the $host.PrivateData.Progress* color configuration variables.Verbose and -Debug parameters, respectively.$debugPreference, $verbosePreference, and $progressPreference shell variables. These variables can accept the following values:Program Files directory) that provides users read access but not write access.InstallUtil SnapinFilename.dll. This command lets all users on the computer load and run commands defined by the snapin. You can find the InstallUtil utility in the .NET Framework's installation directory—commonly C:\WINDOWS\ Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe.Add-PsSnapin SnapinIdentifier. To see all available snapin identifiers, review the names listed in the output of the command:Get-PsSnapin -Registered
InstallUtil /u SnapinFilename.dll. Once uninstalled, you may delete the files associated with the snapin.Add-PsSnapin cmdlet is the most common way to load an individual snapin. To load a preconfigured list of snapins, though, the following section , "Use Console Files to Load and Save Sets of Snapins" offers