Get started with Windows PowerShell
Learn about Windows PowerShell
PowerShell consists of a command-line shell, a scripting language, and a configuration-management framework.
A scripting language
Commands include cmdlets, functions, filters, scripts, applications, configurations, and workflows. Cmdlets use a Verb-Noun naming convention. For example, Get-Command lists all the cmdlets and functions registered in the command shell. "Get" is the action the cmdlet performs, and "Command" is the resource it acts on.
Installing and using PowerShell side-by-side with Windows PowerShell
PowerShell 7 can coexist with Windows PowerShell 5.1. To determine the current version, enter $PSVersionTable and hit Enter.
Identifying and modifying the execution policy in PowerShell
PowerShell's execution policy minimizes the risk of unintentionally running scripts. However, it isn't a security system that restricts user actions. Users can easily bypass a policy by entering the script contents at the command line.
Get-ExecutionPolicy shows the execution policy of the current PowerShell session. You can configure the following policy settings:
- AllSigned - requires a trusted publisher to sign all scripts and prompts you to classify scripts as trusted or untrusted upon execution. Verifying a script's signature doesn't mean it is not malicious.
- Default - sets the default execution policy as Restricted for Windows clients and RemoteSigned for Windows servers.
- RemoteSigned - requires a trusted publisher's digital signature on scripts and configuration files downloaded from the Internet but not on scripts written on the local computer. It's the default execution policy for Windows Server.
- Restricted - allows running individual commands but doesn't allow scripts. It's the default execution policy for Windows client computers.
- Unrestricted - allows unsigned scripts to run. It warns the user before running scripts and configuration files that are not from the local intranet zone. It's the default execution policy for non-Windows computers, which you can't change.
- Undefined - indicates that there isn't an execution policy in the current scope. In this case, the effective policy is "Restricted" for Windows clients and "RemoteSigned" for Windows Server.
To change the execution policy in PowerShell, use the following command:
Set-ExecutionPolicy -ExecutionPolicy <PolicyName>
Discover the structure of PowerShell cmdlets
Cmdlets use the Verb-Noun notation. Common verbs include:
- Get retrieves a resource, such as a file or a user.
- Set changes the data associated with a resource, such as a file or user property.
- New creates a resource, such as a file or user.
- Add adds a resource to a container of multiple resources.
- Remove deletes a resource from a container of multiple resources.
Additionally, some verbs perform similar functions. For example, the Add verb, like the New verb, can create a resource. Some verbs seem similar but have different functions. For example, the Read verb retrieves a resource's information, such as a text file's content, while the Get verb retrieves the actual file.
Cmdlet nouns
A cmdlet's noun indicates the resources or objects the cmdlet affects. For example, the Service noun is for cmdlets that work with Windows services, and the Process noun is for managing processes on a computer.
Nouns also have prefixes that help group related nouns into families. For example, Active Directory nouns begin with the letters AD (such as ADUser, ADGroup, and ADComputer). Microsoft SharePoint Server cmdlets begin with SP, and Microsoft Azure cmdlets begin with Az.
Discover the parameters for using PowerShell cmdlets
Parameters modify the actions that a cmdlet performs. You can specify no parameters, one parameter, or many parameters for a cmdlet.
Parameter format
Parameter names begin with a dash (-). A space separates the parameter name from its value. Wrap the text in quotation marks if its value contains spaces. Some parameters accept multiple values, which you must separate by commas and no spaces.
Optional vs. required parameters
Parameters can be optional or required. If a parameter is required, running the cmdlet without providing its value makes PowerShell prompt you to provide it. For example, running Get-Item returns the following message from PowerShell, which includes a prompt to provide a value for the -Path parameter:
PS C:\> Get-Item
cmdlet Get-Item at command pipeline position 1
Supply values for the following parameters:
Path[0]:
The command successfully runs if you enter the text C:\ at the prompt and press the Enter key twice.
Sometimes, entering the parameter name is optional; you can just enter the parameter's value. Get-ChildItem C:\ is the same as Get-ChildItem -Path C:\ because the parameter -Path is the first parameter in the cmdlet definition. -Path is known as a positional parameter. Omitting the parameter name works with positional parameters but not named parameters. Not all commands have positional parameters.
Switches
Switches are parameters that accept a Boolean value (true or false). They differ from actual Boolean parameters because their value is automatically true when you include them in a command. An example is the -Recurse parameter (switch) of the Get-ChildItem cmdlet. The command Get-ChildItem c:\ -Recurse returns the items in the C:\ directory and subdirectories. Only the items in the C:\ directory display when you omit the -Recurse switch.
Review the tab completion feature in PowerShell
Tab completion improves the speed and ease of finding and entering cmdlets, parameters, variable names, object properties, and file paths. Entering a few characters and pressing the tab key makes PowerShell provide the missing part. If there are multiple matches, press the Tab key multiple times until you see what you want.
Tab completion also helps you discover cmdlet and parameter names. For example, if you want a Get cmdlet that retrieves an Active Directory resource, enter Get-AD and press Tab to review the available options. To find parameters, enter a dash (-) and press the Tab key multiple times to review all the parameters.
Tab completion even works with wildcards. To find a cmdlet that operates on services, enter *-service in the console and press the Tab key to review all cmdlets that contain -service in their names.
Display the About files content in PowerShell
Many help files include information about the PowerShell scripting language, operators, and other details. This information doesn't specifically relate to a single command but to global shell techniques and features.
You can review a complete list of these topics by running Get-Help about* and then review a single topic by running Get-Help about_topicname. An example is Get-Help about_common_parameters. Although these commands aren't compatible with the –Example or –Full parameters of the Help command, they're compatible with the –ShowWindow and –Online parameters.
When you use wildcard characters with Get Help, About help files will appear last in the list. You can also use the ‑Category parameter to specify a search for About files.
Define modules in PowerShell
Modules are groups of related PowerShell capabilities and cmdlets bundled into a single unit. To use a module's cmdlets, load it into the current PowerShell session by running Import-Module.
Autoloading
Modules will load automatically if:
- You run a cmdlet that is part of that module.
- The module that contains the cmdlet is in a folder under the module load paths. By default, these folders include %systemdir%WindowsPowerShellv1.0Modules and %userprofiles%DocumentsWindowsPowerShellModules. The $env:PSModulePath environment variable contains the list of folders. When explicitly importing a module by name, PowerShell checks the locations referenced by that environment variable.
Find cmdlets in PowerShell
Windows PowerShell has built-in help that includes examples and makes learning cmdlets easier.
To determine what cmdlet sets an IP address on a network adapter or disables a user account in Active Directory, start with your knowledge of cmdlet name structure and use Get-Command or Get-Help. Get-Command retrieves information about commands, such as their name, category, version, and even the module that contains it. Get-Help finds help content about commands.
Like the Get-Help command, Get-Command accepts wildcard characters, so Get-Command *event* retrieves a list of command names containing "event." Get-Command also has several parameters to filter the results further. For example, the -Noun and -Verb parameters filter out the cmdlet's noun and verb portions, respectively. Both parameters accept wildcards.
Combining parameters refines the results further. Get-Command –Noun event* –Verb Get lists commands with nouns starting with "event" and using "Get."
When identifying command names, consider just a single-word, singular noun. For example, searching "event" and "log" is effective when finding a command that works with Windows event logs.
Using modules to discover cmdlets
Get-Module and Get-Command -Module list a module's cmdlets.
Suppose you've discovered the module NetAdapter. You can find its applicable commands by running the Get-Command –Module NetAdapter command. The –Module parameter restricts the results to just those commands in the module.
Using Get-Help to discover cmdlets
Get-Help lets you perform similar searches. One advantage of using Get-Help instead of Get-Command is that Get-Help performs a full-text search with your query string if it can't find a command name that matches. For example, Get-Command *beep* returns no results, but Get-Help *beep* returns multiple results.
The Related Links section of the cmdlet's help topics lists cmdlets related to it.
PowerShell Gallery
The PowerShell Gallery is a central repository for Windows PowerShell–related content, including scripts and modules. It uses the PowerShellGet module, which contains cmdlets for finding and installing modules, scripts, and commands from the online gallery. For example, Find-Command searches for commands, functions, and aliases, similar to the Get-Command cmdlet, and includes support for wildcards.
You can pass the results of the Find-Command cmdlet to the Install-Module cmdlet, which the PowerShellGet module also contains. Install-Module will install the module that contains the cmdlet that you discovered.
Use command aliases in PowerShell
Often, you can use CMD commands within Windows PowerShell because, behind the scenes, they run native PowerShell cmdlets. The dir command runs Get-ChildItem, the cd command runs Set-Location, and the mkdir command runs New-Item. These commands work with PowerShell because they're aliases of the equivalent cmdlets.
Aliases and parameters
PowerShell aliases typically don't support the original commands' parameters. For example, the command dir /o:d returns an error because Get-ChildItem doesn't recognize the /o:d parameter. Instead, use dir | sort LastAccessTime to list the contents of the current folder sorted by last accessed date and time in ascending order.
Get-Alias
PowerShell also provides other aliases, such as gci for Get-ChildItem, which replaces a full command with its abbreviated notation. You can use Get-Alias to discover aliases, their definitions, and the commands they run. Get‑Alias with no parameters returns all aliases defined. The -Name parameter, a positional parameter that accepts wildcards, finds specific aliases. For example, Get-Alias -Name di* returns aliases for diff and dir.
You can also use the Get-Alias cmdlet to discover new cmdlets. For example, del deletes a file or folder. Get-Alias del shows that del is an alias for Remove-Item. You can even reverse the discovery process by running Get‑Alias -definition Remove-Item to discover that Remove-Item has several other aliases, including rd, erase, and ri.
Parameters can also have aliases. For example, the -s parameter is an alias for -Recurse in the Get‑ChildItem cmdlet. You can also use partial parameter names if they are enough to identify that parameter uniquely.
New-Alias
New-Alias helps create a custom alias to map to any existing cmdlet. However, remember that PowerShell doesn't save custom aliases between sessions. Use a Windows PowerShell profile to recreate the alias every time you open Windows PowerShell. For more information about creating and using a PowerShell profile, refer to about_Profiles.
Disadvantages of Aliases
Aliases can help you enter commands faster, but they make scripts harder to review and understand. Using tab completion with PowerShell commands is usually as fast as using aliases.
Use Show-Command and Get-Help in PowerShell
Show-Command opens a window that displays a list of commands or a specific command's parameters. To display a specific command's parameters, provide the command's name as the value for the ‑Name parameter. For example, the following command opens a Show-Command window with the command used to retrieve an Active Directory user:
Show-Command –Name Get-ADUser
The –Name parameter is positional, so the following command produces the same result:
Show-Command Get-ADUser
In these examples, Show-Command is the command you're running, but Get-ADUser is the name of the command that you want to review in the dialog box.
Once you provide values for all required parameters, you can run the command immediately by selecting Run in the Show-Commands window. You can also copy it to the Clipboard by selecting Copy and paste the command into the console to review the correct syntax without running the command.
Notice that Show-Command also displays the Windows PowerShell common parameters, a set of parameters that Windows PowerShell adds to all commands to provide a predefined set of core capabilities. You'll learn more about many of the common parameters in upcoming modules. However, to learn about them now, run help about_common_parameters in Windows PowerShell and review the results.
Using Get-Help
You can access the PowerShell help by using the Get-Help command. The Help function and the Man alias map to the Get-Help command, and all three commands return the same results.
For example, to display the help information for the Get-ChildItem cmdlet, enter the following command:
Get-Help Get-ChildItem
Get-Help parameters
The Get-Help command accepts parameters that allow you to find additional information, such as usage examples for a command. For instance, running Get-Help Stop-Process –Examples will provide examples of using the Stop-Process cmdlet.
The -Full parameter provides in-depth information about a cmdlet, including:
- A description of each parameter
- Whether each parameter has a default value
- Whether a parameter is mandatory
- Whether a parameter can accept a value in a specific position (in which case the position number, starting from 1, is given) or whether you must enter the parameter name (in which case named displays)
- Whether a parameter accepts pipeline input and, if so, how
Other Get-Help parameters include:
- ‑ShowWindow. Displays the help topic in a separate window, which makes it much easier to access help while entering commands
- ‑Online. Displays the online version of the help topic (typically the most up-to-date information) in a browser window
- ‑Parameter ParameterName. Displays the description of a named parameter
- ‑Category. Displays help only for certain categories of commands, such as cmdlets and functions.
Using Get-Help to find commands
Get-Help accepts wildcard characters (*, ?). Windows PowerShell will display a list of matching help topics when you use wildcard characters with a partial command name.
If you want all cmdlets that operate on processes, enter Get-Help *process* in the console. The results match the ones returned by the command Get-Command *process*, except that Get-Help displays a synopsis to help you identify the command you want.
A wildcard search may not match any command name. For example, Get-Help *beep* won't find any commands with beep in their name. In this case, the help system will search available command descriptions and synopses to locate any help files containing beep.
Interpret the help file contents and update the local help content in PowerShell
Learning to interpret the help-file syntax can help you identify a given command's capabilities.
Get-EventLog help
Use the help for Get-EventLog as an example. Entering the command Get-Help Get-EventLog in the console returns the following syntax:
Get-EventLog [-LogName] <String> [[-InstanceId] <Int64[]>] [-After <DateTime>] [-AsBaseObject] [-Before <DateTime>] [-ComputerName <String[]>] [-EntryType {Error | Information | FailureAudit | SuccessAudit | Warning}] [-Index <Int32[]>] [-Message <String>] [-Newest <Int32>] [-Source <String[]>] [-UserName <String[]>] [<CommonParameters>]
Get-EventLog [-AsString] [-ComputerName <String[]>] [-List] [<CommonParameters>]
The two blocks of text are parameter sets, each representing how you can run the command. Notice that each parameter set has several parameters in common. You can't mix and match parameters between sets. If you decide to use the –List parameter, you can't also use –LogName because these parameters don't appear together in the same parameter set.
The –LogName parameter name is enclosed in square brackets, meaning it's a positional parameter. You can't run the command without a log name. However, you don't have to enter the –LogName parameter name. You must pass the log name string as the first parameter because that's the position in the help file where the –LogName parameter appears. Therefore, the following two commands provide the same results:
Get-EventLog –LogName Application
Get-EventLog Application
Specifying multiple values
Some parameters accept more than one value. These parameters appear in the SYNTAX section, designated by a double-square-bracket notation in the parameter value type. For example:
-ComputerName <string[]>
The above syntax indicates that the –ComputerName parameter can accept one or more string values. One way to specify multiple values is by using a comma-separated list. Enclose the values in quotation marks if they contain a comma or white space, such as a space or tab character. For example, use the following command to specify multiple computer names:
Get-EventLog –LogName Application –ComputerName LON-CL1,LON-DC1
Run Get-Help Get-EventLog –Full to review the full help for Get-EventLog and notice the additional information displayed. For example, you can confirm that the –LogName parameter is mandatory and appears in the first position.
Updating help
Run Update-Help to scan your computer for all installed modules, retrieve online help locations for each, and try to download their respective help files. You must run this command as a member of the local Administrators group because Windows PowerShell core command help is in the %systemdir% folder.
The companion to Update-Help is Save-Help. It downloads the help content and saves it to a specified location so you can copy it to computers that aren't Internet-connected.
Windows PowerShell Study Guide
PowerShell Quiz
Instructions: Answer the following questions in 2-3 sentences each.
- What is a cmdlet in PowerShell, and how is it structured?
- Explain the difference between the 'Get' and 'Read' verbs in PowerShell cmdlets.
- What is PowerShell's execution policy, and how can you determine the current policy setting?
- Describe the difference between required and optional parameters in PowerShell cmdlets.
- What are switches in PowerShell, and how do they differ from Boolean parameters?
- Explain how tab completion can be useful when working with PowerShell.
- What is the purpose of modules in PowerShell, and how can you load a module?
- Explain the difference between the 'Get-Command' and 'Get-Help' cmdlets.
- What is an alias in PowerShell, and what cmdlet can you use to discover them?
- Describe the function of the 'Show-Command' cmdlet and how it can be helpful.
PowerShell Quiz Answer Key
- A cmdlet is a lightweight command used in the Windows PowerShell environment. It follows a Verb-Noun naming convention, such as 'Get-ChildItem', where 'Get' is the verb and 'ChildItem' is the noun.
- Both retrieve information, but 'Get' retrieves the actual resource (e.g., a file), while 'Read' retrieves information about the resource (e.g., the file's content).
- It minimizes the risk of unintentionally running scripts by controlling the conditions under which they can run. The cmdlet 'Get-ExecutionPolicy' can determine the current policy setting.
- Required parameters are essential for a cmdlet to function, and PowerShell will prompt you for their values if you do not provide them. Optional parameters modify the cmdlet's behavior but are not mandatory for execution.
- Switches are parameters that accept a Boolean value (true or false). Unlike Boolean parameters, their value defaults to 'true' simply by being included in a command.
- It simplifies and speeds up command entry by suggesting cmdlets, parameters, variables, properties, and file paths. Pressing Tab after entering a few characters triggers PowerShell to complete the rest.
- Modules are packages of related PowerShell functionality and cmdlets grouped for convenient organization and use. The 'Import-Module' cmdlet loads a module into the current PowerShell session.
- 'Get-Command' retrieves information about available commands, while 'Get-Help' provides detailed information about a specific command, including its syntax and examples.
- An alias is an alternate name or shortcut for a cmdlet or command. The 'Get-Alias' cmdlet is used to discover existing aliases and their corresponding commands.
- 'Show-Command' opens a graphical dialog box displaying a list of commands or the parameters of a specific command. This allows users to visually construct and review commands before execution.
PowerShell Essay Questions
- Discuss the different execution policy settings in PowerShell and their security implications. When would you use each policy?
- Explain the concept of parameter sets in PowerShell cmdlets. How do parameter sets provide flexibility in using a single cmdlet for different purposes?
- Describe the different ways to discover cmdlets in PowerShell. Explain how you would approach finding a cmdlet for a specific task.
- Discuss the advantages and disadvantages of using aliases in PowerShell. When is it appropriate to use aliases, and when is it better to use the full cmdlet name?
- Explain how to use the 'Get-Help' cmdlet effectively to retrieve comprehensive information about a PowerShell command, including its syntax, parameters, and examples.
Comments
Post a Comment