Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering PowerShell Scripting

You're reading from   Mastering PowerShell Scripting Automate repetitive tasks and simplify complex administrative tasks using PowerShell

Arrow left icon
Product type Paperback
Published in May 2024
Publisher Packt
ISBN-13 9781805120278
Length 826 pages
Edition 5th Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Chris Dent Chris Dent
Author Profile Icon Chris Dent
Chris Dent
Arrow right icon
View More author details
Toc

Table of Contents (23) Chapters Close

Preface 1. Introduction to PowerShell FREE CHAPTER 2. Modules 3. Variables, Arrays, and Hashtables 4. Working with Objects in PowerShell 5. Operators 6. Conditional Statements and Loops 7. Working with .NET 8. Files, Folders, and the Registry 9. Windows Management Instrumentation 10. Working with HTML, XML, and JSON 11. Web Requests and Web Services 12. Remoting and Remote Management 13. Asynchronous Processing 14. Graphical User Interfaces 15. Scripts, Functions, and Script Blocks 16. Parameters, Validation, and Dynamic Parameters 17. Classes and Enumerations 18. Testing 19. Error Handling 20. Debugging 21. Other Books You May Enjoy
22. Index

Getting help

PowerShell includes a built-in help system accessible using the Get-Help command. Help content in PowerShell is often rich and detailed, frequently including multiple examples. Gaining confidence using the built-in help system is an important part of working with PowerShell. Script authors and PowerShell developers can easily write their own help content when working with functions, scripts, and script modules.

Updatable help

The concept of updatable help was added in Windows PowerShell 3. It allows users to obtain the most recent versions of their help documentation outside of PowerShell on a web service. Help content can be downloaded and installed using the Update-Help command in PowerShell.

Which modules support updatable help?

The command below shows a list of modules that support updatable help:

Get-Module -ListAvailable | Where-Object HelpInfoURI

Help for the core components of PowerShell is not part of the PowerShell 7 installation package. Content must be downloaded before it can be viewed.

The first time Get-Help runs, PowerShell prompts to update help.

Computers with no internet access or computers behind a restrictive proxy server may not be able to download help content directly. The Save-Help command can be used in this scenario, which is discussed later in this section, to work around the problem.

If PowerShell is unable to download help, it can only show a small amount of information about a command; for example, without downloading help, the content for the Out-Null command is minimal, as shown here:

PS> Get-Help Out-Null
NAME
    Out-Null
  
SYNTAX
    Out-Null [-InputObject <psobject>] [<CommonParameters>]
  
ALIASES
    None
  
REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer.
    It is displaying only partial help.
        -- To download and install Help files for the module that
           includes this cmdlet, use Update-Help.
        -- To view the Help topic for this cmdlet online, type:
           "Get-Help Out-Null -Online" or go to
           http://go.microsoft.com/fwlink/?LinkID=113366.

The help content in the preceding example is automatically generated by PowerShell. PowerShell inspects the command to determine which parameters are available.

Updatable help as a help file can be viewed using the following command:

Get-Help about_Updatable_Help

Updateable help is not entirely free from issues. Internet resources change as content moves around over time, which may invalidate HelpInfoUri, the URL stored within the module and used to retrieve help files. For example, help for the Dism module was not available when this chapter was written.

The Get-Help command

When Get-Help is used without parameters, it shows introductory help about the help system. This content is taken from the default help file (Get-Help default); a snippet of this is as follows:

PS> Get-Help
TOPIC
 PowerShell Help System
SHORT DESCRIPTION
 Displays help about PowerShell cmdlets and concepts.
LONG DESCRIPTION
 PowerShell Help describes Windows PowerShell cmdlets, functions,

Help content can be long

The help content, in most cases, does not fit on a single screen. The help command differs from Get-Help in that it pauses (waiting for a key to be pressed) after each page; for example:

help default

The previous command is equivalent to running Get-Help and piping it into the more command:

Get-Help default | more

Alternatively, Get-Help can be asked to show a window:

Get-Help default -ShowWindow

The available help content may be listed using either of the following two commands:

Get-Help *
Get-Help -Category All

Help for a subject can be viewed as follows:

Get-Help -Name <Topic>

For example, help for the Get-Variable command may be shown:

Get-Help Get-Variable

If a help document includes an online version link, it may be opened in a browser with the -Online parameter:

Get-Help Get-Command -Online

The URL used for online help can be viewed using Get-Command:

Get-Command Get-Command | Select-Object HelpUri

The help content is broken down into several sections: name, synopsis, syntax, description, related links, and remarks.

Name simply includes the name of the command. Synopsis is a short description of the functionality provided by the command, often no more than one sentence. Description often provides much greater detail than synopsis. Related links and remarks are optional fields, which may include links to related content.

Syntax is covered in the following section in more detail as it is the most complex part of the help document. A good understanding of the syntax allows quick evaluation of how to use a command, often removing the need to do more than skim help content.

Syntax

The syntax section lists each of the possible combinations of parameters a command accepts; each of these is known as a parameter set.

A command that has more than one parameter set is shown in this example for the Get-Process command:

SYNTAX
    Get-Process [[-Name] <System.String[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]
    Get-Process [-FileVersionInfo] -Id <System.Int32[]> [-Module] [<CommonParameters>]

The syntax elements written in square brackets are optional; for example, syntax help for Get-Process shows that all its parameters are optional, as the following code shows:

SYNTAX
    Get-Process [[-Name] <System.String[]>] [-FileVersionInfo] [-Module] [<CommonParameters>]

As the Name parameter is optional, Get-Process may be run without any parameters. The command may also be run by specifying a value only and no parameter name. Alternatively, the parameter name can be included as well as the value.

Each of the following examples is a valid use of Get-Process:

Get-Process
Get-Process pwsh
Get-Process -Name pwsh

Get-Command can show syntax

Get-Command may be used to view the syntax for a command. For example, running the following command will show the same output as seen in the Syntax section of Get-Help:

Get-Command Get-Variable -Syntax

The different parameter types and how they are used are explored later in this chapter.

Examples

The Examples section of help provides working examples of how a command may be used. Help often includes more than one example.

In some cases, a command is sufficiently complex that it requires a detailed example to accompany parameter descriptions; in others, the command is simple, and a good example may serve in lieu of reading the help documentation.

PowerShell users can update help

Help documentation for built-in commands is open source. If a cmdlet is missing helpful examples, they can be added.

A link to the PowerShell-Docs repository is available at the bottom of the online help page. It should send you to the en-US version of help:

https://github.com/MicrosoftDocs/PowerShell-Docs.

Examples for a command can be requested by specifying the Examples parameter for Get-Help, as shown in the following example:

Get-Help Get-Process -Examples

The help information for most cmdlets usually includes several examples of their use, especially if the command has more than one parameter set.

Parameter

Parameters in PowerShell are used to supply named arguments to PowerShell commands.

Help for specific parameters can be requested as follows:

Get-Help Get-Command -Parameter <ParameterName>

The Parameter parameter allows for the quick retrieval of specific help for a single parameter; for example, help for the Path parameter of the Import-Csv command may be viewed:

PS> Get-Help Import-Csv -Parameter Path
-Path [<String[]>]
    Specifies the path to the CSV file to import. You can also
    pipe a path to `Import-Csv`.
  
    Required? false
    Position? 1
    Default value None
    Accept pipeline input? true (ByValue)
    Accept wildcard characters? false

This avoids needing to scroll through a potentially large help file to see how to use just one parameter.

The preceding content describes the parameter, whether the parameter is mandatory (Required), its position, default value, pipeline behavior, and support for wildcards.

Detailed and Full switches

The Detailed switch parameter (a parameter that does not require an argument) asks Get-Help to return the most help content.

The default sections returned by help are Name, Synopsis, Syntax, Description, Related Links, and Remarks.

When Detailed is requested, Parameters and Examples are added. Related Links is excluded.

The Detailed parameter is used as follows:

Get-Help Get-Process -Detailed

The Full switch parameter includes all the default sections, as well as Parameters, Inputs, Outputs, Notes, and Examples.

The following code shows the sections detailing the input and output types for Get-Process from the full help document; content before those sections has been removed from this example:

PS> Get-Help Get-Process -Full
... <content removed> ...
INPUTS
    System.Diagnostics.Process
        You can pipe a process object to Get-Process.
OUTPUTS
    System.Diagnostics.Process
        By default, this cmdlet returns a
        System.Diagnostics.Process object.
    System.Diagnotics.FileVersionInfo
        If you use the FileVersionInfo parameter, this cmdlet
        returns a FileVersionInfo object.
    System.Diagnostics.ProcessModule
        If you use the Module parameter, without the
        FileVersionInfo parameter, this cmdlet returns a
        ProcessModule object. 

INPUTS is typically used to describe the value types that can be piped to a command. Pipelines are introduced in Chapter 4, Working with Objects in PowerShell.

In addition to the extra sections, the Full switch parameter includes metadata in the parameter section, the same parameter metadata seen when using Get-Help Get-Process -Parameter Name.

Help content in PowerShell is extensive and a valuable resource to have on any system running PowerShell.

Save-Help

The Save-Help command can be used with modules that support updatable help. It allows help content for installed modules to be saved to disk.

Help for a module can be downloaded using the following command. The destination folder must exist before running the command:

New-Item -Path C:\PSHelp -ItemType Directory
Save-Help -Module Microsoft.PowerShell.Management -DestinationPath C:\PSHelp

By default, Save-Help attempts to download help content for the current UI culture; that is, the current user interface language. The Get-UICulture command can be used to view the current culture, as the following example shows:

PS> Get-UICulture
LCID             Name             DisplayName
----             ----             -----------
2057             en-GB            English (United Kingdom)

If help content is not available for that culture, Save-Help will not do anything and will not raise an error. For UI cultures other than en-US, the C:\PSHelp folder will likely be empty.

Save-Help can be instructed to download help in a specific language by using the UICulture parameter:

Save-Help -Module Microsoft.PowerShell.Management -DestinationPath C:\PSHelp -UICulture en-US

If help content is available, it is downloaded as shown in the C:\PSHelp folder here:

Figure 1.5: Downloaded help content for en-US

By default, Save-Help (and Update-Help) will not download help content more often than once every 24 hours as a rate-limiting control. This can be seen using the Verbose switch parameter:

PS> Save-Help -Module Microsoft.PowerShell.Management -DestinationPath C:\PSHelp -UICulture en-US -Verbose
VERBOSE: Help was not saved for the module Microsoft.PowerShell.Management, because the Save-Help command was run on this computer within the last 24 hours.

The Verbose switch parameter is used to make any verbose messages the command author has included visible in the console.

If help content is available for other cultures, and that content is downloaded immediately after en-US, then the Force parameter must be added:

Save-Help -Module Microsoft.PowerShell.Management -DestinationPath C:\PSHelp -UICulture pl-PL -Force

However, as help content for the Microsoft.PowerShell.Management module is only available in en-US, the preceding command displays an error message describing which cultures help is available for.

Help content for all modules supporting updateable help can be saved as follows:

Save-Help -DestinationPath C:\PSHelp -UICulture en-US

Saved help content can be copied to another computer and imported using Update-Help. This technique is useful for computers that do not have internet access as it means help content can be made available.

Update-Help

The Update-Help command performs two tasks:

  • Update help files on the local computer from the internet.
  • Updates help files on the local computer from previously saved help files.

To update help from the internet for all modules that support updateable help, run the Update-Help cmdlet with no parameters:

Update-Help

The Update-Help command includes a Scope parameter, which may be used to make help content available without needing Administrative access:

Update-Help -Scope CurrentUser

When the Scope parameter is set to CurrentUser, help content is downloaded to and read from (by Get-Help) $home\Documents\PowerShell\help. This path may be affected by folder redirection of the Documents folders, such as with services like OneDrive.

The Scope parameter is not available in Windows PowerShell and administrative rights are required to update help content.

For UI cultures other than en-US, the UICulture parameter may be required:

Update-Help -UICulture en-US

Like Save-Help, Update-Help will not download help for a module more than once every 24 hours by default. This can be overridden by using the Force parameter:

Update-Help -Name Microsoft.PowerShell.Management -Force -UICulture en-US

Help content that was saved using Save-Help can be imported from a folder using the SourcePath parameter:

Update-Help -SourcePath C:\PSHelp

If the folder does not contain content for the current UI culture (shown with Get-UICulture), an error message will be displayed:

PS> Update-Help -Module Microsoft.PowerShell.Management -SourcePath C:\PSHelp
Update-Help: Failed to update Help for the module(s) 'Microsoft.PowerShell.Management' with UI culture(s) {en-GB} : Unable to retrieve the HelpInfo XML file for UI culture en-GB. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again..

The UICulture parameter can be used again to update help content from the folder:

Update-Help -Module Microsoft.PowerShell.Management -SourcePath C:\PSHelp -UICulture en-US

Help content is not limited to help for specific commands. PowerShell includes many topical help documents.

About_* help files

About_* documents describe features of the language or concepts that apply to more than one command. These items do not fit into help for individual commands.

The list of help files can be viewed by running Get-Help with the category set to HelpFile, as demonstrated in the following code:

Get-Help -Category HelpFile

Alternatively, wildcards can be used with the Name parameter of Get-Help:

Get-Help -Name About_*

These help files cover a huge variety of topics ranging from aliases to modules to WMI. A number of these are shown here. The list will vary, depending on the modules installed on the computer running the command:

Name                         Category  Module  Synopsis
----                         --------  ------  --------
default                      HelpFile          SHORT DESCRIPTION
about_PSReadLine             HelpFile                
about_Configuration          HelpFile          The Configuratio...
about_Aliases                HelpFile                          
about_Alias_Provider         HelpFile                          
about_Arithmetic_Operators   HelpFile                          
about_Arrays                 HelpFile                          
about_Assignment_Operators   HelpFile                          
about_Automatic_Variables    HelpFile                          
about_Break                  HelpFile                          

Using help content is an important part of working with PowerShell. Memorizing content is not necessary where instructions and reference material are easily accessible.

Get-Help may lead to finding a command to help achieve a task; however, it is often quicker to search using Get-Command.

You have been reading a chapter from
Mastering PowerShell Scripting - Fifth Edition
Published in: May 2024
Publisher: Packt
ISBN-13: 9781805120278
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image