Chapter 26: Tips, tricks, and techniques
This section explains how PowerShell profile scripts customize shell startup and how their location, host, and execution policy affect when they run.
After this chapter you will be able to
- Profile startup and customization. Explain that a hosting application loads profile scripts when the shell starts, and that those scripts can run commands to customize the environment.
- Profile file scope and selection. Distinguish profiles that apply to all users or only the current user, and profiles shared across hosts or specific to a host. Explain why the file chosen matters when using both the console and VS Code.
- Prompt function customization. Explain that PowerShell generates its prompt with a built-in function called Prompt, which you can replace with your own function in a profile script to use it each time you open the shell.
- Message colors and profiles. Explain how changing error, warning, and other message colors differs from changing default window colors, and how to make a message-color change recur when opening the shell.
- Type conversion with -as. Explain how -as attempts to convert an existing object to a specified type, including the order of the object, operator, and bracketed type.
- Type checking with -is. Describe what -is returns when checking whether an object is of a particular type.
- Regex replacement syntax and behavior. Explain how to use -replace to replace all occurrences of matching text in a source string, and distinguish its regex matching from the string replace() method's static text replacement.
- Joining array elements. Explain how -join turns an array into a delimited string, such as a pipe-delimited string.
- Splitting delimited strings. Explain how -split turns a delimited string into an array, including how the section specifies a tab delimiter and accesses the resulting elements.
- Wildcard Matching and Collection Membership. Distinguish -like from -contains when checking strings, and explain how -in performs the same membership test as -contains with the operands reversed.
- Useful string method operations. Describe what IndexOf(), ToLower(), ToUpper(), Trim(), TrimStart(), and TrimEnd() do, and explain that methods can be called on either a string variable or a static string. Distinguish the Split(), Join(), and Replace() methods from the similarly operating PowerShell operators that the authors prefer.
- DateTime properties and methods. Distinguish using DateTime properties to access a day, month, or year from using methods to calculate or format dates. Explain that AddDays() with a negative number finds an earlier date and that To methods format dates according to the computer’s regional settings.
- WMI Date Conversion. Explain why WMI dates need conversion and how a WMI object's date-conversion methods help turn them into normal date and time values. Describe how a converted value can be included in a table.
- Default parameter values variable. Explain that $PSDefaultParameterValues holds user-defined parameter defaults and starts empty in each new shell window; a profile script can populate it for future sessions.
- Default matching and assigned values. Describe how an Add() entry identifies a cmdlet and parameter, including wildcard matching, and how its second argument supplies either a fixed default value or a script block that runs commands.
- Script block syntax and execution. Explain how to recognize a script block, distinguish it from a hash table, and run one stored in a variable.
- Incremental PowerShell skill development. Explain how picking up tips bit by bit, through experience and sources such as community forums, can help you continually improve with PowerShell.
What it builds on
- Execution policy (chapter 4) · The earlier explanation of PowerShell execution policy.
- Using variables: Fun tricks with quotes (chapter 16) · Using variables in double-quoted strings.
- A regex syntax primer (chapter 21) · The basic idea of regular-expression matching.
- Working with multiple objects in a variable (chapter 16) · Working with multiple objects stored in a variable
- Using comparison operators (chapter 12) · Using comparison operators in PowerShell.
- Using object actions, or methods (chapter 8) · The idea that objects have methods.
- Using object attributes, or properties (chapter 8) · Using object properties to access values
- Discovering objects: Get-Member (chapter 8) · Using Get-Member to discover an object's methods.
Section by section
Introduction
26.1 Profiles, prompts, and colors: Customizing the shell
26.1.1 PowerShell profiles
This section explains how PowerShell profile scripts customize shell startup and how their location, host, and execution policy affect when they run.
- Profile startup and customization: Explain that a hosting application loads profile scripts when the shell starts, and that those scripts can run commands to customize the environment.
Why it matters: A profile can set up the commands and starting location you want each time you open PowerShell. - Profile file scope and selection: Distinguish profiles that apply to all users or only the current user, and profiles shared across hosts or specific to a host. Explain why the file chosen matters when using both the console and VS Code.
Why it matters: Choosing the right profile file lets your setup appear in the intended shells without applying it to the wrong users or hosts. - Profile testing and execution limits: Describe how to inspect and test profiles, and explain how execution policy can prevent a profile from running.
Why it matters: These checks help you tell whether you chose the right profile and why it did not run.
Key terms: hosting application, PowerShell engine, profile scripts, $pshome, $home, console host, VS Code, profile.ps1, $Profile, Format-List -force
26.1.2 Customizing the prompt
This subsection explains how the Prompt function generates PowerShell’s prompt and how a profile script can customize it.
- Prompt function customization: Explain that PowerShell generates its prompt with a built-in function called Prompt, which you can replace with your own function in a profile script to use it each time you open the shell.
Why it matters: You can make the prompt show information useful to you without redefining it every session. - Default prompt components: Describe how the default Prompt function displays debug context, the current location, and an indication of a nested prompt.
Why it matters: The default prompt shows how a prompt function can reflect the shell’s current state. - Alternative prompt contents: Describe the alternative prompt’s displayed information and explain why double-quoted strings can include variable values.
Why it matters: Variable expansion lets a custom prompt display changing information rather than fixed text.
Key terms: Prompt, profile script, $DebugContext, VARIABLE: drive, Get-Location, $nestedpromptlevel, nested prompt, double quotation marks, $time, current computer name
26.1.3 Tweaking colors
This subsection shows how to change PowerShell’s default window colors and message colors.
- Default window text colors: Describe how to change the default text foreground and background colors in the PowerShell window.
Why it matters: You can adjust the shell’s everyday appearance without running a command. - Message colors and profiles: Explain how changing error, warning, and other message colors differs from changing default window colors, and how to make a message-color change recur when opening the shell.
Why it matters: A profile can reapply your preferred message colors whenever you start PowerShell.
Key terms: foreground, background, Properties, Colors tab, profile, ErrorForegroundColor, WarningForegroundColor
26.2 Operators: -as, -is, -replace, -join, -split, -contains, -in
26.2.1 -as and -is
This subsection introduces -as for converting an object to another type and -is for checking an object's type.
- Type conversion with -as: Explain how -as attempts to convert an existing object to a specified type, including the order of the object, operator, and bracketed type.
Why it matters: It lets you request a different type for a value without confusing rounding with truncation. - Type checking with -is: Describe what -is returns when checking whether an object is of a particular type.
Why it matters: It distinguishes a type test from the conversion attempted by -as.
Key terms: -as, type, casting, [int], -is, True, False
26.2.2 -replace
Explains how PowerShell's -replace operator uses a regular expression to replace matching text and how it differs from the string replace() method.
- Regex replacement syntax and behavior: Explain how to use -replace to replace all occurrences of matching text in a source string, and distinguish its regex matching from the string replace() method's static text replacement.
Why it matters: The matching rule and argument order determine which text gets replaced.
Key terms: -replace operator, regex, source string, string replace() method
26.2.3 -join and -split
This section shows how to turn an array into a delimited string with -join and turn a delimited string back into an array with -split.
- Joining array elements: Explain how -join turns an array into a delimited string, such as a pipe-delimited string.
Why it matters: Joining makes an array usable as a single delimited value. - Splitting delimited strings: Explain how -split turns a delimited string into an array, including how the section specifies a tab delimiter and accesses the resulting elements.
Why it matters: Splitting lets you work with individual values from a delimited line.
Key terms: -join, array, pipe-delimited string, -split, tab-delimited, backtick, `t, index numbers
26.2.4 -contains and -in
Distinguishes wildcard string matching from collection membership tests and explains the operand order for -contains and -in.
- Wildcard Matching and Collection Membership: Distinguish -like from -contains when checking strings, and explain how -in performs the same membership test as -contains with the operands reversed.
Why it matters: Choosing the right operator avoids confusing a wildcard string comparison with a test for membership in a collection.
Key terms: -like, -contains, -in, wildcard string comparisons, collection, operands
26.3 String manipulation
This section shows how to discover and use methods on PowerShell strings to find text, change case, and remove whitespace.
- String methods and discovery: Explain that PowerShell strings are objects with methods, and describe how to discover those methods by piping a string to gm.
Why it matters: You can find a string’s available actions instead of memorizing every method. - Useful string method operations: Describe what IndexOf(), ToLower(), ToUpper(), Trim(), TrimStart(), and TrimEnd() do, and explain that methods can be called on either a string variable or a static string. Distinguish the Split(), Join(), and Replace() methods from the similarly operating PowerShell operators that the authors prefer.
Why it matters: These methods let you make common text changes without writing a separate text-processing routine.
Key terms: strings, objects, methods, gm, IndexOf(), ToLower(), ToUpper(), Trim(), TrimStart(), TrimEnd()
26.4 Date manipulation
This section shows how DateTime properties and methods provide date parts, calculate dates, and format dates and times.
- DateTime properties and methods: Distinguish using DateTime properties to access a day, month, or year from using methods to calculate or format dates. Explain that AddDays() with a negative number finds an earlier date and that To methods format dates according to the computer’s regional settings.
Why it matters: Choosing a property or method lets you get the date information or result you need.
Key terms: DateTime, properties, methods, AddDays(), To
26.5 Dealing with WMI dates
Explains how to make WMI date strings usable in Windows PowerShell 5.1 and contrasts them with date values returned by CIM commands.
- WMI Date Conversion: Explain why WMI dates need conversion and how a WMI object's date-conversion methods help turn them into normal date and time values. Describe how a converted value can be included in a table.
Why it matters: Converting the value makes a WMI date easier to use and display. - CIM Date Handling: Distinguish the date handling described for CIM commands from that of WMI.
Why it matters: The distinction helps explain when manual attention to date conversion may be needed.
Key terms: WMI, ConvertFromDateTime(), ConvertToDateTime(), Select-Object, Format-Table, calculated columns and properties, CIM commands, date/time values
26.6 Setting default parameter values
This section shows how to set default PowerShell parameter values and explains when those defaults apply.
- Default parameter values variable: Explain that $PSDefaultParameterValues holds user-defined parameter defaults and starts empty in each new shell window; a profile script can populate it for future sessions.
Why it matters: This lets you avoid repeatedly supplying parameters while understanding why your settings may disappear in a new window. - Default matching and assigned values: Describe how an Add() entry identifies a cmdlet and parameter, including wildcard matching, and how its second argument supplies either a fixed default value or a script block that runs commands.
Why it matters: Matching lets you choose whether a default affects one command or many, while a script block can produce a value when needed. - Session and script scope: Distinguish defaults set at the command line from defaults set within a script in terms of where they apply.
Why it matters: Script-local defaults can simplify a script without changing how other scripts or shell commands behave.
Key terms: $PSDefaultParameterValues, hash table, profile script, Add(), wildcards, script block, -Credential, Get-Credential, scope, shell session
26.7 Playing with script blocks
The section identifies where script blocks appear in familiar PowerShell commands and shows how to recognize, store, and run one.
- Script block syntax and execution: Explain how to recognize a script block, distinguish it from a hash table, and run one stored in a variable.
Why it matters: Recognizing a script block helps you understand what you are passing to a command and how to run one yourself. - Script blocks in commands: Describe some of the places this section identifies script blocks in PowerShell commands.
Why it matters: These examples connect script blocks to commands you have already encountered.
Key terms: script block, curly brackets, hash table, call operator, Where-Object, ForEach-Object, Expression, -ScriptBlock
26.8 More tips, tricks, and techniques
The section encourages readers to keep improving their PowerShell skills by picking up useful tips over time.
- Incremental PowerShell skill development: Explain how picking up tips bit by bit, through experience and sources such as community forums, can help you continually improve with PowerShell.
Why it matters: You do not need to learn every technique at once to keep getting better with PowerShell.
Key terms: tips and techniques, PowerShell.org, incrementally
Concepts explained in this chapter
- PowerShell profileA PowerShell profile is a user-specific script that runs when a PowerShell session starts and can configure the session environment.
- PowerShell hostA PowerShell host is an interface environment or application that receives PowerShell output and provides interaction with a PowerShell session.
- quotation marksA double quotation mark delimits a PowerShell expandable string in which variable references can be replaced by their values.
- stringA string, represented by the .NET System.String type, is a sequence of characters representing text data.
- default valueA default parameter value is an input automatically supplied to a command parameter when the caller does not provide one.
- scopeScope is the region of a script or session in which a variable or other name is accessible.
- methodA method is a callable operation associated with an object that can direct the object to perform an action.
- Windows Management InstrumentationWMI is Windows Management Instrumentation, a Windows management technology for querying and administering system resources.
- arrayAn array is an ordered collection of values that can be accessed as a single sequence.
- script blockA script block is a PowerShell language construct that groups executable statements inside braces for invocation or deferred execution.
- atomic typeA data type defines the kind of value represented and the operations applicable to that value.
- comparisonA comparison is an expression that evaluates a relationship between values and produces a Boolean result.
- collectionA collection is a container that groups multiple values as a single data object.
- data conversionCasting is the operation of treating a value as a specified type, optionally converting it to an object of that type.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
