Updates from: 07/28/2021 03:13:45
Service Microsoft Docs article Related commit history on GitHub Change details
Microsoft.PowerShell.Core About Functions Advanced Parameters (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Parameters.md
description: Explains how to add parameters to advanced functions. keywords: powershell,cmdlet Locale: en-US Previously updated : 10/27/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Functions Advanced Parameters
that has the following characteristics:
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
+## Switch parameters
+
+Switch parameters are parameters that take no parameter value.
+Instead, they convey a Boolean true-or-false value through their presence or absence,
+so that when a switch parameter is present it has a **true** value
+and when absent it has a **false** value.
+
+For example, the **Recurse** parameter of `Get-ChildItem` is a switch
+parameter.
+
+To create a switch parameter in a function, specify the `switch` type in the
+parameter definition.
+
+For example, your function may have an option to output data as a byte array:
+
+```powershell
+Param([switch]$AsByteArray)
+```
+
+Switch parameters are easy to use and are preferred over Boolean parameters,
+which have a less natural syntax for PowerShell.
+
+For example, to use a switch parameter, the user types the parameter in the
+command.
+
+`-IncludeAll`
+
+To use a Boolean parameter, the user types the parameter and a Boolean value.
+
+`-IncludeAll $true`
+
+When creating switch parameters, choose the parameter name carefully. Be sure
+that the parameter name communicates the effect of the parameter to the user.
+Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
+value is required.
+
+### Switch parameter design considerations
+
+- Switch parameters should not be given default values. They should always
+ default to false.
+- Switch parameters should be designed so that setting them moves a command
+ from its default functionality to a less common or more complicated mode. The
+ simplest behavior of a command should be the default behavior that does not
+ require the use of switch parameters.
+- Switch parameters should not be mandatory, since that defeats the purpose of
+ a switch; a mandatory switch can only take one value. The only case where is
+ is necessary to make a switch parameter mandatory is when it is needed to
+ differentiate a parameter set. In this case, the switch parameter must be
+ mandatory.
+- Explicitly setting a switch from a boolean can be done with
+ `-MySwitch:$boolValue` and in splatting with
+ `$params = @{ MySwitch = $boolValue }`.
+- Switch parameters are of type `SwitchParameter` but implicitly convert to
+ Boolean. The parameter variable can be used directly in a conditional
+ expression. For example:
+
+ `if ($MySwitch) { ... }`
+
+ There's no need to write `if ($MySwitch.IsPresent) { ... }`
+
+## Dynamic parameters
+
+Dynamic parameters are parameters of a cmdlet, function, or script that are
+available only under certain conditions.
+
+For example, several provider cmdlets have parameters that are available only
+when the cmdlet is used in the provider drive, or in a particular path of the
+provider drive. For example, the **Encoding** parameter is available on the
+`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
+a file system drive.
+
+You can also create a parameter that appears only when another parameter is
+used in the function command or when another parameter has a certain value.
+
+Dynamic parameters can be useful, but use them only when necessary because
+they can be difficult for users to discover. To find a dynamic parameter, the
+user must be in the provider path, use the **ArgumentList** parameter of the
+`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
+
+To create a dynamic parameter for a function or script, use the `DynamicParam`
+keyword.
+
+The syntax is as follows:
+
+`dynamicparam {<statement-list>}`
+
+In the statement list, use an `if` statement to specify the conditions under
+which the parameter is available in the function.
+
+The following example shows a function with standard parameters named **Name**
+and **Path**, and an optional dynamic parameter named **KeyCount**. The
+**KeyCount** parameter is in the `ByRegistryPath` parameter set and has a type
+of `Int32`. The **KeyCount** parameter is available in the `Get-Sample`
+function only when the value of the **Path** parameter starts with `HKLM:`,
+indicating that it's being used in the `HKEY_LOCAL_MACHINE` registry drive.
+
+```powershell
+function Get-Sample {
+ [CmdletBinding()]
+ Param([string]$Name, [string]$Path)
+
+ DynamicParam
+ {
+ if ($Path.StartsWith("HKLM:"))
+ {
+ $parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
+ ParameterSetName = "ByRegistryPath"
+ Mandatory = $false
+ }
+
+ $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
+ $attributeCollection.Add($parameterAttribute)
+
+ $dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
+ 'KeyCount', [Int32], $attributeCollection
+ )
+
+ $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
+ $paramDictionary.Add('KeyCount', $dynParam1)
+ return $paramDictionary
+ }
+ }
+}
+```
+
+For more information, see the documentation for the
+[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter)
+type.
+ ## Attributes of parameters This section describes the attributes that you can add to function parameters.
The following example declares the **ComputerName** parameter. It uses the
```powershell Param( [Parameter(Mandatory=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
value in the command.
```powershell Param( [Parameter(Position=0)]
- [String[]]
+ [string[]]
$ComputerName ) ```
parameter set, a **UserName** parameter in the `User` parameter set, and a
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false)]
- [Switch]
+ [switch]
$Summary ) ```
the `Computer` parameter set and mandatory in the `User` parameter set.
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false, ParameterSetName="Computer")] [Parameter(Mandatory=$true, ParameterSetName="User")]
- [Switch]
+ [switch]
$Summary ) ```
and accepts an object that's passed to the function from the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
the function through the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
for the function (for example, `.SYNOPSIS`) then this message also shows up in
Param( [Parameter(Mandatory=$true, HelpMessage="Enter one or more computer names separated by commas.")]
- [String[]]
+ [string[]]
$ComputerName ) ```
The following example shows a parameter declaration that adds the **CN** and
Param( [Parameter(Mandatory=$true)] [Alias("CN","MachineName")]
- [String[]]
+ [string[]]
$ComputerName ) ```
for a mandatory **Path** parameter that supports wildcard values.
Param( [Parameter(Mandatory=$true)] [SupportsWildcards()]
- [String[]]
+ [string[]]
$Path ) ```
developer must implement the code to handle the wildcard input. The wildcards
supported can vary according to the underlying API or PowerShell provider. For more information, see [about_Wildcards](about_Wildcards.md).
-### Parameter and variable validation attributes
+### ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion. Similar to **DynamicParameters**, the
+available values are calculated at runtime when the user presses <kbd>Tab</kbd>
+after the parameter name.
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompleter-attribute).
+
+## Parameter and variable validation attributes
Validation attributes direct PowerShell to test the parameter values that users submit when they call the advanced function. If the parameter values fail the
test, an error is generated and the function isn't called. Parameter validation
is only applied to the input provided and any other values like default values are not validated.
-You can also use the validation attributes to restrict the values that
-users can specify for variables. When you use a type converter along with a
-validation attribute, the type converter has to be defined before the attribute.
+You can also use the validation attributes to restrict the values that users
+can specify for variables. When you use a type converter along with a
+validation attribute, the type converter has to be defined before the
+attribute.
```powershell [int32][AllowNull()] $number = 7 ```
+> [!NOTE]
+> Validation attributes can be applied to any variable, not just parameters.
+> You can define validation for any variable within a script.
+ ### AllowNull validation attribute The **AllowNull** attribute allows the value of a mandatory parameter to be
parameter that can have an empty string value.
Param( [Parameter(Mandatory=$true)] [AllowEmptyString()]
- [String]
+ [string]
$ComputerName ) ```
parameter to be an empty collection `@()`. The following example declares a
Param( [Parameter(Mandatory=$true)] [AllowEmptyCollection()]
- [String[]]
+ [string[]]
$ComputerName ) ```
takes one to five parameter values.
Param( [Parameter(Mandatory=$true)] [ValidateCount(1,5)]
- [String[]]
+ [string[]]
$ComputerName ) ```
In the following example, each computer name must have one to ten characters.
Param( [Parameter(Mandatory=$true)] [ValidateLength(1,10)]
- [String[]]
+ [string[]]
$ComputerName ) ```
and each digit must be a number zero to nine.
Param( [Parameter(Mandatory=$true)] [ValidatePattern("[0-9][0-9][0-9][0-9]")]
- [String[]]
+ [string[]]
$ComputerName ) ```
four-digit number, and each digit must be a number zero to nine.
The **ValidateRange** attribute specifies a numeric range for each parameter or variable value. PowerShell generates an error if any value is outside that
-range. In the following example, the value of the **Attempts** parameter must
-be between zero and ten.
+range.
+
+In the following example, the value of the **Attempts** parameter must be
+between zero and ten.
```powershell Param(
High.
Param( [Parameter(Mandatory=$true)] [ValidateSet("Low", "Average", "High")]
- [String[]]
+ [string[]]
$Detail ) ```
Chocolate, Strawberry, or Vanilla.
```powershell [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
-[String]$flavor = "Strawberry"
+[string]$flavor = "Strawberry"
``` The validation occurs whenever that variable is assigned even within the
script. For example, the following results in an error at runtime:
```powershell Param( [ValidateSet("hello", "world")]
- [String]$Message
+ [string]$Message
) $Message = "bye" ```
+This example returns the following error at runtime:
+
+```Output
+The attribute cannot be added because variable Message with value bye would no
+longer be valid.
+At line:1 char:1
++ [ValidateSet("hello", "world")][string]$Message = 'bye'++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ + CategoryInfo : MetadataError: (:) [], ValidationMetadataException
+ + FullyQualifiedErrorId : ValidateSetFailure
+
+```
+
+Using `ValidateSet` also enable tab expansion of values for that parameter. For
+more information, see [about_Tab_Expansion](about_Tab_Expansion.md).
+
+#### Dynamic ValidateSet values using classes
+
+You can use a **Class** to dynamically generate the values for **ValidateSet**
+at runtime. In the following example, the valid values for the variable
+`$Sound` are generated via a **Class** named **SoundNames** that checks three
+filesystem paths for available sound files:
+
+```powershell
+Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
+ [string[]] GetValidValues() {
+ $SoundPaths = '/System/Library/Sounds/',
+ '/Library/Sounds','~/Library/Sounds'
+ $SoundNames = ForEach ($SoundPath in $SoundPaths) {
+ If (Test-Path $SoundPath) {
+ (Get-ChildItem $SoundPath).BaseName
+ }
+ }
+ return [string[]] $SoundNames
+ }
+}
+```
+
+The `[SoundNames]` class is then implemented as a dynamic **ValidateSet** value
+as follows:
+
+```powershell
+Param(
+ [ValidateSet([SoundNames])]
+ [string]$Sound
+)
+```
+
+> [!NOTE]
+> The `IValidateSetValuesGenerator` class was introduced in PowerShell 6.0
+ ### ValidateNotNull validation attribute The **ValidateNotNull** attribute specifies that the parameter value can't be
empty string (`""`), or an empty array `@()`.
Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
- [String[]]
+ [string[]]
$UserName ) ```
If you use relative path, the current drive must be in the allowed drive list.
```powershell Param( [ValidateDrive("C", "D", "Variable", "Function")]
- [String]$Path
+ [string]$Path
) ```
If you use relative path, the current drive must be `User`.
function Test-UserDrivePath{ [OutputType([bool])] Param(
- [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][String]$Path
+ [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][string]$Path
) $True }
This attribute was added in PowerShell 6.1.1.
At this time, the attribute is used internally by PowerShell itself and is not intended for external usage.
-## Dynamic parameters
-
-Dynamic parameters are parameters of a cmdlet, function, or script that are
-available only under certain conditions.
-
-For example, several provider cmdlets have parameters that are available only
-when the cmdlet is used in the provider drive, or in a particular path of the
-provider drive. For example, the **Encoding** parameter is available on the
-`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
-a file system drive.
-
-You can also create a parameter that appears only when another parameter is
-used in the function command or when another parameter has a certain value.
-
-Dynamic parameters can be useful, but use them only when necessary, because
-they can be difficult for users to discover. To find a dynamic parameter, the
-user must be in the provider path, use the **ArgumentList** parameter of the
-`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
-
-To create a dynamic parameter for a function or script, use the `DynamicParam`
-keyword.
-
-The syntax is as follows:
-
-`DynamicParam {<statement-list>}`
-
-In the statement list, use an `If` statement to specify the conditions under
-which the parameter is available in the function.
-
-Use the `New-Object` cmdlet to create a
-**System.Management.Automation.RuntimeDefinedParameter** object to represent
-the parameter and specify its name.
-
-You can use a `New-Object` command to create a
-**System.Management.Automation.ParameterAttribute** object to represent
-attributes of the parameter, such as **Mandatory**, **Position**, or
-**ValueFromPipeline** or its parameter set.
-
-The following example shows a sample function with standard parameters named
-**Name** and **Path**, and an optional dynamic parameter named **DP1**. The
-**DP1** parameter is in the `PSet1` parameter set and has a type of `Int32`.
-The **DP1** parameter is available in the `Get-Sample` function only when the
-value of the **Path** parameter starts with `HKLM:`, indicating that it's being
-used in the `HKEY_LOCAL_MACHINE` registry drive.
-
-```powershell
-function Get-Sample {
- [CmdletBinding()]
- Param([String]$Name, [String]$Path)
-
- DynamicParam
- {
- if ($Path.StartsWith("HKLM:"))
- {
- $attributes = New-Object -Type `
- System.Management.Automation.ParameterAttribute
- $attributes.ParameterSetName = "PSet1"
- $attributes.Mandatory = $false
- $attributeCollection = New-Object `
- -Type System.Collections.ObjectModel.Collection[System.Attribute]
- $attributeCollection.Add($attributes)
-
- $dynParam1 = New-Object -Type `
- System.Management.Automation.RuntimeDefinedParameter("DP1", [Int32],
- $attributeCollection)
-
- $paramDictionary = New-Object `
- -Type System.Management.Automation.RuntimeDefinedParameterDictionary
- $paramDictionary.Add("DP1", $dynParam1)
- return $paramDictionary
- }
- }
-}
-```
-
-For more information, see
-[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter).
-
-## Switch parameters
-
-Switch parameters are parameters with no parameter value. They're effective
-only when they're used and have only one effect.
-
-For example, the **NoProfile** parameter of **powershell.exe** is a switch
-parameter.
-
-To create a switch parameter in a function, specify the `Switch` type in the
-parameter definition.
-
-For example:
-
-```powershell
-Param([Switch]<ParameterName>)
-```
-
-Or, you can use an another method:
-
-```powershell
-Param(
- [Parameter(Mandatory=$false)]
- [Switch]
- $<ParameterName>
-)
-```
-
-Switch parameters are easy to use and are preferred over Boolean parameters,
-which have a more difficult syntax.
-
-For example, to use a switch parameter, the user types the parameter in the
-command.
-
-`-IncludeAll`
-
-To use a Boolean parameter, the user types the parameter and a Boolean value.
-
-`-IncludeAll:$true`
-
-When creating switch parameters, choose the parameter name carefully. Be sure
-that the parameter name communicates the effect of the parameter to the user.
-Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
-value is required.
-
-## ArgumentCompleter attribute
-
-The **ArgumentCompleter** attribute allows you to add tab completion values to
-a specific parameter. An **ArgumentCompleter** attribute must be defined for
-each parameter that needs tab completion. Similar to **DynamicParameters**, the
-available values are calculated at runtime when the user presses <kbd>Tab</kbd>
-after the parameter name.
-
-To add an **ArgumentCompleter** attribute, you need to define a script block
-that determines the values. The script block must take the following
-parameters in the order specified below. The parameter's names don't matter as
-the values are provided positionally.
-
-The syntax is as follows:
-
-```powershell
-Param(
- [Parameter(Mandatory)]
- [ArgumentCompleter({
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
- # Perform calculation of tab completed values here.
- })]
-)
-```
-
-### ArgumentCompleter script block
-
-The script block parameters are set to the following values:
--- `$commandName` (Position 0) - This parameter is set to the name of the
- command for which the script block is providing tab completion.
-- `$parameterName` (Position 1) - This parameter is set to the parameter whose
- value requires tab completion.
-- `$wordToComplete` (Position 2) - This parameter is set to value the user has
- provided before they pressed <kbd>Tab</kbd>. Your script block should use
- this value to determine tab completion values.
-- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
- Tree (AST) for the current input line. For more information, see
- [Ast Class](/dotnet/api/system.management.automation.language.ast).
-- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
- containing the `$PSBoundParameters` for the cmdlet, before the user pressed
- <kbd>Tab</kbd>. For more information, see
- [about_Automatic_Variables](about_Automatic_Variables.md).
-
-The **ArgumentCompleter** script block must unroll the values using the
-pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
-Returning an array of values causes PowerShell to treat the entire array as
-**one** tab completion value.
-
-The following example adds tab completion to the **Value** parameter. If only
-the **Value** parameter is specified, all possible values, or arguments, for
-**Value** are displayed. When the **Type** parameter is specified, the
-**Value** parameter only displays the possible values for that type.
-
-In addition, the `-like` operator ensures that if the user types the following
-command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
-
-`Test-ArgumentCompleter -Type Fruits -Value A`
-
-```powershell
-function Test-ArgumentCompleter {
-[CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ValidateSet('Fruits', 'Vegetables')]
- $Type,
- [Parameter(Mandatory=$true)]
- [ArgumentCompleter( {
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
-
- $possibleValues = @{
- Fruits = @('Apple', 'Orange', 'Banana')
- Vegetables = @('Tomato', 'Squash', 'Corn')
- }
- if ($fakeBoundParameters.ContainsKey('Type'))
- {
- $possibleValues[$fakeBoundParameters.Type] | Where-Object {
- $_ -like "$wordToComplete*"
- }
- }
- else
- {
- $possibleValues.Values | ForEach-Object {$_}
- }
- } )]
- $Value
- )
-}
-```
- ## See also [about_Automatic_Variables](about_Automatic_Variables.md)
Microsoft.PowerShell.Core About Functions Argument Completion (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions_Argument_Completion.md
+---
Last updated : 07/27/2021
+description: Explains the various argument completion options available for function parameters.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_Functions_Argument_Completion?view=powershell-5.1&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About functions argument completion
+---
+# about_Functions_Argument_Completion
+
+## Short description
+Argument completion is a feature of PowerShell that provide hints, enables
+discovery, and speeds up input entry of argument values.
+
+## Long description
+
+This article describe the different ways you can implement argument completers
+for PowerShell functions. Argument completers provide the possible values for a
+parameter. The available values are calculated at runtime when the user presses
+the <kbd>Tab</kbd> key after the parameter name. There are several ways to
+define an argument completer for a parameter.
+
+> [!NOTE]
+> <kbd>Tab</kbd> is the default key binding on Windows. This keybinding can be
+> changed by the PSReadLine module or the application that is hosting
+> PowerShell. The keybinding is different on non-Windows platforms. For more
+> information, see
+> [about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+## ValidateSet attribute
+
+The **ValidateSet** attribute specifies a set of valid values for a parameter
+or variable and enables tab completion. PowerShell generates an error if a
+parameter or variable value doesn't match a value in the set. In the following
+example, the value of the **Fruit** parameter can only be **Apple**,
+**Banana**, or **Pear**.
+
+```powershell
+Param(
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Apple', 'Banana', 'Pear')]
+ [string[]]
+ $Fruit
+)
+```
+
+In the following example, the value of the variable `$flavor` must be either
+**Chocolate**, **Strawberry**, or **Vanilla**. The `ValidateSet` attribute can
+be used on any variable, not just parameters.
+
+```powershell
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')]
+[string]$flavor = 'Strawberry'
+```
+
+The validation occurs whenever that variable is assigned even within the
+script.
+
+```powershell
+Param(
+ [ValidateSet('hello', 'world')]
+ [string]$Message
+)
+
+$Message = 'bye'
+```
+
+This example returns the following error at runtime:
+
+```
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+For more information about tab expansion, see
+[about_Tab_Expansion](about_Tab_Expansion.md).
+
+### Dynamic ValidateSet values using classes
+
+You can use a **Class** to dynamically generate the values for **ValidateSet**
+at runtime. In the following example, the valid values for the variable
+`$Sound` are generated via a **Class** named **SoundNames** that checks three
+filesystem paths for available sound files:
+
+```powershell
+Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
+ [string[]] GetValidValues() {
+ $SoundPaths = '/System/Library/Sounds/',
+ '/Library/Sounds',
+ '~/Library/Sounds'
+ $SoundNames = ForEach ($SoundPath in $SoundPaths) {
+ If (Test-Path $SoundPath) {
+ (Get-ChildItem $SoundPath).BaseName
+ }
+ }
+ return [string[]] $SoundNames
+ }
+}
+```
+
+The `[SoundNames]` class is then implemented as a dynamic **ValidateSet** value
+as follows:
+
+```powershell
+Param(
+ [ValidateSet([SoundNames])]
+ [string]$Sound
+)
+```
+
+> [!NOTE]
+> The `IValidateSetValuesGenerator` class was introduced in PowerShell 6.0.
+
+## ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion.
+
+To add an **ArgumentCompleter** attribute, you need to define a script block
+that determines the values. The script block must take the following
+parameters in the order specified below. The parameter's names don't matter as
+the values are provided positionally.
+
+The syntax is as follows:
+
+```powershell
+function MyArgumentCompleter {
+ Param(
+ [Parameter(Mandatory)]
+ [ArgumentCompleter( {
+ param ( $commandName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+ # Perform calculation of tab completed values here.
+ } )]
+ $ParamName
+ )
+}
+```
+
+### ArgumentCompleter script block
+
+The script block parameters are set to the following values:
+
+- `$commandName` (Position 0) - This parameter is set to the name of the
+ command for which the script block is providing tab completion.
+- `$parameterName` (Position 1) - This parameter is set to the parameter whose
+ value requires tab completion.
+- `$wordToComplete` (Position 2) - This parameter is set to value the user has
+ provided before they pressed <kbd>Tab</kbd>. Your script block should use
+ this value to determine tab completion values.
+- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
+ Tree (AST) for the current input line. For more information, see the
+ [AST](/dotnet/api/system.management.automation.language.ast) type
+ documentation.
+- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
+ containing the `$PSBoundParameters` for the cmdlet, before the user pressed
+ <kbd>Tab</kbd>. For more information, see
+ [about_Automatic_Variables](about_Automatic_Variables.md).
+
+The **ArgumentCompleter** script block must unroll the values using the
+pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
+Returning an array of values causes PowerShell to treat the entire array as
+**one** tab completion value.
+
+The following example adds tab completion to the **Value** parameter. If only
+the **Value** parameter is specified, all possible values, or arguments, for
+**Value** are displayed. When the **Type** parameter is specified, the
+**Value** parameter only displays the possible values for that type.
+
+In addition, the `-like` operator ensures that if the user types the following
+command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
+
+`Test-ArgumentCompleter -Type Fruits -Value A`
+
+```powershell
+function MyArgumentCompleter{
+ param ( $commaName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+
+ $possibleValues = @{
+ Fruits = @('Apple', 'Orange', 'Banana')
+ Vegetables = @('Tomato', 'Squash', 'Corn')
+ }
+
+ if ($fakeBoundParameters.ContainsKey('Type')) {
+ $possibleValues[$fakeBoundParameters.Type] | Where-Object {
+ $_ -like "$wordToComplete*"
+ }
+ } else {
+ $possibleValues.Values | ForEach-Object {$_}
+ }
+}
+
+function Test-ArgumentCompleter {
+[CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompleter({ MyArgumentCompleter @args })]
+ $Value
+ )
+}
+```
+
+## Register-ArgumentCompleter
+
+The `Register-ArgumentCompleter` cmdlet registers a custom argument completer.
+An argument completer allows you to provide dynamic tab completion, at run time
+for any command that you specify.
+
+For more information, see
+[Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter).
+
+## See also
+
+- [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md)
+- [Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter)
+- [about_Tab_Expansion](about_Tab_Expansion.md)
Microsoft.PowerShell.Core About Remote Requirements (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md
---
-description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
+description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
keywords: powershell,cmdlet Locale: en-US Previously updated : 01/03/2018 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_requirements?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Requirements
Title: about Remote Requirements
# about_Remote_Requirements
-## SHORT DESCRIPTION
-
+## Short description
Describes the system requirements and configuration requirements for running remote commands in PowerShell.
-## LONG DESCRIPTION
+## Long description
This topic describes the system requirements, user requirements, and resource requirements for establishing remote connections and running remote commands in PowerShell. It also provides instructions for configuring remote operations.
-Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject,
-Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by
-using Microsoft .NET Framework methods to retrieve the objects. They do not
-use the PowerShell remoting infrastructure. The requirements in this
-document do not apply to these cmdlets.
+> [!NOTE]
+> Many cmdlets (including the `Get-Service`, `Get-Process`, `Get-WMIObject`,
+> `Get-EventLog`, and `Get-WinEvent` cmdlets) get objects from remote computers
+> by using Microsoft .NET Framework methods to retrieve the objects. They do
+> not use the PowerShell remoting infrastructure. The requirements in this
+> document do not apply to these cmdlets.
-To find the cmdlets that have a ComputerName parameter but do not use Windows
-PowerShell remoting, read the description of the ComputerName parameter of the
-cmdlets.
+To find the cmdlets that have a **ComputerName** parameter but do not use
+Windows PowerShell remoting, read the description of the **ComputerName**
+parameter of the cmdlets.
-## SYSTEM REQUIREMENTS
+## System requirements
To run remote sessions on Windows PowerShell 3.0, the local and remote computers must have the following:
PowerShell 3.0, such as the ability to disconnect and reconnect to sessions,
are available only when both computers are running Windows PowerShell 3.0. To find the version number of an installed version of PowerShell,
-use the $PSVersionTable automatic variable.
+use the `$PSVersionTable` automatic variable.
Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are included in Windows 8, Windows Server 2012, and newer releases of the Windows
operating system. WinRM 3.0 is included in Windows Management Framework 3.0
for older operating systems. If the computer does not have the required version of WinRM or the Microsoft .NET Framework, the installation fails.
-## USER PERMISSIONS
+## User permissions
To create remote sessions and run remote commands, by default, the current
-user must be a member of the Administrators group on the remote computer or
+user must be a member of the **Administrators** group on the remote computer or
provide the credentials of an administrator. Otherwise, the command fails. The permissions required to create sessions and run commands on a remote computer (or in a remote session on the local computer) are established by the
-session configuration (also known as an "endpoint") on the remote computer to
+session configuration (also known as an **endpoint**) on the remote computer to
which the session connects. Specifically, the security descriptor on the session configuration determines who has access to the session configuration and who can use it to connect. The security descriptors on the default session configurations,
-Microsoft.PowerShell, Microsoft.PowerShell32, and
-Microsoft.PowerShell.Workflow, allow access only to members of the
-Administrators group.
+**Microsoft.PowerShell**, **Microsoft.PowerShell32**, and
+**Microsoft.PowerShell.Workflow**, allow access only to members of the
+**Administrators** group.
If the current user doesn't have permission to use the session configuration, the command to run a command (which uses a temporary session) or create a
persistent session on the remote computer fails. The user can use the
ConfigurationName parameter of cmdlets that create sessions to select a different session configuration, if one is available.
-Members of the Administrators group on a computer can determine who has
+Members of the **Administrators** group on a computer can determine who has
permission to connect to the computer remotely by changing the security descriptors on the default session configurations and by creating new session configurations with different security descriptors.
configurations with different security descriptors.
For more information about session configurations, see [about_Session_Configurations](about_Session_Configurations.md).
-## WINDOWS NETWORK LOCATIONS
+## Windows network locations
-Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable
+Beginning in Windows PowerShell 3.0, the `Enable-PSRemoting` cmdlet can enable
remoting on client and server versions of Windows on private, domain, and public networks. On server versions of Windows with private and domain networks, the
-Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted remote
+`Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted remote
access. It also creates a firewall rule for public networks that allows remote access only from computers in the same local subnet. This local subnet firewall rule is enabled by default on server versions of Windows on public
-networks, but Enable-PSRemoting reapplies the rule in case it was changed or
+networks, but `Enable-PSRemoting` reapplies the rule in case it was changed or
deleted. On client versions of Windows with private and domain networks, by default,
-the Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted
+the `Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted
remote access. To enable remoting on client versions of Windows with public networks, use the
-SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates
+**SkipNetworkProfileCheck** parameter of the `Enable-PSRemoting` cmdlet. It creates
a firewall rule that allows remote access only from computers in the same local subnet. To remove the local subnet restriction on public networks and allow remote access from all locations on client and server versions of Windows, use the
-Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following
+`Set-NetFirewallRule` cmdlet in the **NetSecurity** module. Run the following
command: ```powershell Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any ```
-In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling the
+> firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+
+In Windows PowerShell 2.0, on server versions of Windows, `Enable-PSRemoting`
creates firewall rules that permit remote access on all networks.
-In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting
+In Windows PowerShell 2.0, on client versions of Windows, `Enable-PSRemoting`
creates firewall rules only on private and domain networks. If the network
-location is public, Enable-PSRemoting fails.
+location is public, `Enable-PSRemoting` fails.
-## RUN AS ADMINISTRATOR
+## Run as administrator
Administrator privileges are required for the following remoting operations:
Administrator privileges are required for the following remoting operations:
the settings in the LocalHost node of the WSMAN: drive. To perform these tasks, you must start PowerShell with the "Run as
-administrator" option even if you are a member of the Administrators group on
+administrator" option even if you are a member of the **Administrators** group on
the local computer. In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with
-the "Run as administrator" option:
+the **Run as administrator** option:
1. Click Start, click All Programs, click Accessories, and then click the Windows PowerShell folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+1. Right-click Windows PowerShell, and then click **Run as administrator**.
-To start Windows PowerShell with the "Run as administrator" option:
+To start Windows PowerShell with the **Run as administrator** option:
1. Click Start, click All Programs, and then click the Windows PowerShell folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+1. Right-click Windows PowerShell, and then click **Run as administrator**.
-The "Run as administrator" option is also available in other Windows Explorer
+The **Run as administrator** option is also available in other Windows Explorer
entries for Windows PowerShell, including shortcuts. Just right-click the
-item, and then click "Run as administrator".
+item, and then click **Run as administrator**.
When you start Windows PowerShell from another program such as Cmd.exe, use
-the "Run as administrator" option to start the program.
+the **Run as administrator** option to start the program.
-## HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING
+## How to configure your computer for remoting
Computers running all supported versions of Windows can establish remote connections to and run remote commands in PowerShell without any
remoting on the computer.
Windows Server 2012 and newer releases of Windows Server are enabled for PowerShell remoting by default. If the settings are changed, you can
-restore the default settings by running the Enable-PSRemoting cmdlet.
+restore the default settings by running the `Enable-PSRemoting` cmdlet.
On all other supported versions of Windows, you need to run the
-Enable-PSRemoting cmdlet to enable PowerShell remoting.
+`Enable-PSRemoting` cmdlet to enable PowerShell remoting.
The remoting features of PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for
configuration that allow users to connect to WS-Management.
To configure PowerShell to receive remote commands:
-1. Start PowerShell with the "Run as administrator" option.
-2. At the command prompt, type: `Enable-PSRemoting`
+1. Start PowerShell with the **Run as administrator** option.
+1. At the command prompt, type: `Enable-PSRemoting`
To verify that remoting is configured correctly, run a test command such as the following command, which creates a remote session on the local computer.
If remoting is configured correctly, the command will create a session on the
local computer and return an object that represents the session. The output should resemble the following sample output:
-```output
+```Output
Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell
Id Name ComputerName State ConfigurationName
If the command fails, for assistance, see [about_Remote_Troubleshooting](about_Remote_Troubleshooting.md).
-## UNDERSTAND POLICIES
+## Understand policies
When you work remotely, you use two instances of PowerShell, one on the local computer and one on the remote computer. As a result, your work is
In general, before you connect and as you are establishing the connection, the
policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect.
-## SEE ALSO
+## See also
[about_Remote](about_Remote.md)
Microsoft.PowerShell.Core About Remote Troubleshooting (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Remote_Troubleshooting.md
description: Describes how to troubleshoot remote operations in PowerShell. keywords: powershell,cmdlet Locale: en-US Previously updated : 10/27/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Troubleshooting
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
The `Set-NetFirewallRule` cmdlet is exported by the NetSecurity module.
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling
+> the firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+ > [!NOTE] > In Windows PowerShell 2.0, on computers running server versions of Windows, > `Enable-PSRemoting` creates firewall rules that allow remote access on
Microsoft.PowerShell.Core About Tab Expansion (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Tab_Expansion.md
+---
Last updated : 07/27/2021
+description: Explains how to use the Tab Expansion feature in PowerShell.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_tab_expansion?view=powershell-5.1&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About tab expansion
+---
+# about_Tab_Expansion
+
+## Short description
+PowerShell provides completions on input to provide hints, enable discovery, and
+speed up input entry. Command names, parameter names, argument values, and file
+paths can all be completed by pressing the <kbd>Tab</kbd> key.
+
+## Long description
+
+Tab expansion is controlled by the internal function **TabExpansion** or
+**TabExpansion2**. Since this function can be modified or overridden, this
+discussion is a guide to the behavior of the default PowerShell configuration.
+
+The <kbd>Tab</kbd> key is the default key binding on Windows. This keybinding
+can be changed by the PSReadLine module or the application that is hosting
+PowerShell. The keybinding is different on non-Windows platforms. For more
+information, see
+[about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+> [!NOTE]
+> One limitation of the tab expansion process is that tabs are always
+> interpreted as attempts to complete a word. If you copy and paste command
+> examples into a PowerShell console, make sure that the sample does not
+> contain tabs; if it does, the results will be unpredictable and will almost
+> certainly not be what you intended.
+
+## File and cmdlet name completion
+
+To fill in a filename or path from the available choices automatically, type
+part of the name and press the <kbd>Tab</kbd> key. PowerShell will
+automatically expand the name to the first match that it finds. Pressing the
+<kbd>Tab</kbd> key repeatedly will cycle through all of the available choices.
+
+The tab expansion of cmdlet names is slightly different. To use tab expansion
+on a cmdlet name, type the entire first part of the name (the verb) and the
+hyphen that follows it. You can fill in more of the name for a partial match.
+For example, if you type `get-co` and then press the <kbd>Tab</kbd> key,
+PowerShell will automatically expand this to the `Get-Command` cmdlet (notice
+that it also changes the case of letters to their standard form). If you press
+<kbd>Tab</kbd> key again, PowerShell replaces this with the only other matching
+cmdlet name, `Get-Content`.
+
+Tab completion also works to resolve PowerShell alias and native executables.
+
+You can use tab expansion repeatedly on the same line. For example, you can use
+tab expansion on the name of the `Get-Content` cmdlet by entering:
+
+### Examples
+
+```
+PS> Get-Con<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content
+```
+
+You can then partially specify the path to the Active Setup log file and use
+tab expansion again:
+
+```
+PS> Get-Content c:\windows\acts<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content C:\windows\actsetup.log
+```
+
+PSReadLine also has a menu completion feature. The default key binding on
+Windows is <kbd>Ctrl</kbd>-<kbd>Space</kbd>.
+
+```
+PS> fore<Ctrl-Space>
+```
+
+When you press <kbd>Ctrl</kbd>-<kbd>Space</kbd>, PowerShell presents the full
+list of matching values as a menu:
+
+```
+PS> foreach
+foreach ForEach-Object foreach.cmd
+```
+
+In this example the string 'fore' is matched to `foreach` (PowerShell alias),
+`ForEach-Object` (cmdlet), and `foreach.cmd` (native command). Use the arrow
+keys to select the value you want.
+
+## Parameter argument completion
+
+Tab completion can also work to complete parameter arguments. This allows you
+to use the <kbd>Tab</kbd> key to cycle through a list of possible values that
+are valid for some parameter.
+
+For more information see,
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md).
+
+## See also
+
+- [about_Functions_Argument_Completion](about_Functions_Argument_Completion.md)
+- [about_Requires](about_Requires.md)
+- [about_Comment_Based_Help](about_Comment_Based_Help.md)
Microsoft.PowerShell.Core Foreach Object (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/ForEach-Object.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 09/08/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: ForEach-Object
the property value type.
### Example 7: Split module names into component names
-This examples shows three ways to split two dot-separated module names into their component names.
+This example shows three ways to split two dot-separated module names into their component names.
+The commands call the **Split** method of strings. The three commands use different syntax, but they
+are equivalent and interchangeable. The output is the same for all three cases.
```powershell "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
PowerShell
Host ```
-The commands call the **Split** method of strings. The three commands use different syntax, but they
-are equivalent and interchangeable.
- The first command uses the traditional syntax, which includes a script block and the current object operator `$_`. It uses the dot syntax to specify the method and parentheses to enclose the delimiter argument. The second command uses the **MemberName** parameter to specify the **Split** method and the
-**ArgumentName** parameter to identify the dot (".") as the split delimiter.
+**ArgumentList** parameter to identify the dot (`.`) as the split delimiter.
The third command uses the **Foreach** alias of the `ForEach-Object` cmdlet and omits the names of the **MemberName** and **ArgumentList** parameters, which are optional. ### Example 8: Using ForEach-Object with two script blocks
-In this example we pass two script blocks positionally. All the script blocks bind to the
+In this example, we pass two script blocks positionally. All the script blocks bind to the
**Process** parameter. However, they are treated as if they had been passed to the **Begin** and **Process** parameters.
process
### Example 9: Using ForEach-Object with more than two script blocks
-In this example we pass two script blocks positionally. All the script blocks bind to the
+In this example, we pass two script blocks positionally. All the script blocks bind to the
**Process** parameter. However, they are treated as if they had been passed to the **Begin**, **Process**, and **End** parameters.
Accept wildcard characters: False
Specifies the property to get or the method to call. Wildcard characters are permitted, but work only if the resulting string resolves to a unique value.
-If, for example, you run `Get-Process | ForEach -MemberName *Name`, and more than one member exists
-with a name that contains the string Name, such as the **ProcessName** and **Name** properties, the
-command fails.
+For example, if you run `Get-Process | ForEach -MemberName *Name`, the wildcard pattern matches more
+than one member causing the command to fail.
This parameter was introduced in Windows PowerShell 3.0.
Microsoft.PowerShell.Core New Pssession (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/New-PSSession.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Last updated 12/20/2019
Microsoft.PowerShell.Core About Functions Advanced Parameters (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Parameters.md
description: Explains how to add parameters to advanced functions. keywords: powershell,cmdlet Locale: en-US Previously updated : 07/12/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Functions Advanced Parameters
that has the following characteristics:
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
+## Switch parameters
+
+Switch parameters are parameters that take no parameter value.
+Instead, they convey a Boolean true-or-false value through their presence or absence,
+so that when a switch parameter is present it has a **true** value
+and when absent it has a **false** value.
+
+For example, the **Recurse** parameter of `Get-ChildItem` is a switch
+parameter.
+
+To create a switch parameter in a function, specify the `switch` type in the
+parameter definition.
+
+For example, your function may have an option to output data as a byte array:
+
+```powershell
+Param([switch]$AsByteArray)
+```
+
+Switch parameters are easy to use and are preferred over Boolean parameters,
+which have a less natural syntax for PowerShell.
+
+For example, to use a switch parameter, the user types the parameter in the
+command.
+
+`-IncludeAll`
+
+To use a Boolean parameter, the user types the parameter and a Boolean value.
+
+`-IncludeAll $true`
+
+When creating switch parameters, choose the parameter name carefully. Be sure
+that the parameter name communicates the effect of the parameter to the user.
+Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
+value is required.
+
+### Switch parameter design considerations
+
+- Switch parameters should not be given default values. They should always
+ default to false.
+- Switch parameters should be designed so that setting them moves a command
+ from its default functionality to a less common or more complicated mode. The
+ simplest behavior of a command should be the default behavior that does not
+ require the use of switch parameters.
+- Switch parameters should not be mandatory, since that defeats the purpose of
+ a switch; a mandatory switch can only take one value. The only case where is
+ is necessary to make a switch parameter mandatory is when it is needed to
+ differentiate a parameter set. In this case, the switch parameter must be
+ mandatory.
+- Explicitly setting a switch from a boolean can be done with
+ `-MySwitch:$boolValue` and in splatting with
+ `$params = @{ MySwitch = $boolValue }`.
+- Switch parameters are of type `SwitchParameter` but implicitly convert to
+ Boolean. The parameter variable can be used directly in a conditional
+ expression. For example:
+
+ `if ($MySwitch) { ... }`
+
+ There's no need to write `if ($MySwitch.IsPresent) { ... }`
+
+## Dynamic parameters
+
+Dynamic parameters are parameters of a cmdlet, function, or script that are
+available only under certain conditions.
+
+For example, several provider cmdlets have parameters that are available only
+when the cmdlet is used in the provider drive, or in a particular path of the
+provider drive. For example, the **Encoding** parameter is available on the
+`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
+a file system drive.
+
+You can also create a parameter that appears only when another parameter is
+used in the function command or when another parameter has a certain value.
+
+Dynamic parameters can be useful, but use them only when necessary, because
+they can be difficult for users to discover. To find a dynamic parameter, the
+user must be in the provider path, use the **ArgumentList** parameter of the
+`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
+
+To create a dynamic parameter for a function or script, use the `DynamicParam`
+keyword.
+
+The syntax is as follows:
+
+`dynamicparam {<statement-list>}`
+
+In the statement list, use an `if` statement to specify the conditions under
+which the parameter is available in the function.
+
+The following example shows a function with standard parameters named **Name**
+and **Path**, and an optional dynamic parameter named **KeyCount**. The
+**KeyCount** parameter is in the `ByRegistryPath` parameter set and has a type
+of `Int32`. The **KeyCount** parameter is available in the `Get-Sample`
+function only when the value of the **Path** parameter starts with `HKLM:`,
+indicating that it's being used in the `HKEY_LOCAL_MACHINE` registry drive.
+
+```powershell
+function Get-Sample {
+ [CmdletBinding()]
+ Param([string]$Name, [string]$Path)
+
+ DynamicParam
+ {
+ if ($Path.StartsWith("HKLM:"))
+ {
+ $parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
+ ParameterSetName = "ByRegistryPath"
+ Mandatory = $false
+ }
+
+ $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
+ $attributeCollection.Add($parameterAttribute)
+
+ $dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
+ 'KeyCount', [Int32], $attributeCollection
+ )
+
+ $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
+ $paramDictionary.Add('KeyCount', $dynParam1)
+ return $paramDictionary
+ }
+ }
+}
+```
+
+For more information, see the documentation for the
+[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter)
+type.
+ ## Attributes of parameters This section describes the attributes that you can add to function parameters.
The following example declares the **ComputerName** parameter. It uses the
```powershell Param( [Parameter(Mandatory=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
value in the command.
```powershell Param( [Parameter(Position=0)]
- [String[]]
+ [string[]]
$ComputerName ) ```
parameter set, a **UserName** parameter in the `User` parameter set, and a
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false)]
- [Switch]
+ [switch]
$Summary ) ```
the `Computer` parameter set and mandatory in the `User` parameter set.
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false, ParameterSetName="Computer")] [Parameter(Mandatory=$true, ParameterSetName="User")]
- [Switch]
+ [switch]
$Summary ) ```
and accepts an object that's passed to the function from the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
the function through the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
for the function (for example, `.SYNOPSIS`) then this message also shows up in
Param( [Parameter(Mandatory=$true, HelpMessage="Enter one or more computer names separated by commas.")]
- [String[]]
+ [string[]]
$ComputerName ) ```
The following example shows a parameter declaration that adds the **CN** and
Param( [Parameter(Mandatory=$true)] [Alias("CN","MachineName")]
- [String[]]
+ [string[]]
$ComputerName ) ```
for a mandatory **Path** parameter that supports wildcard values.
Param( [Parameter(Mandatory=$true)] [SupportsWildcards()]
- [String[]]
+ [string[]]
$Path ) ```
developer must implement the code to handle the wildcard input. The wildcards
supported can vary according to the underlying API or PowerShell provider. For more information, see [about_Wildcards](about_Wildcards.md).
-### Parameter and variable validation attributes
+## Argument completion attributes
+
+### ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated.
+
+This attribute was introduced in PowerShell Core 6.0
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompletions-attribute).
+
+### ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion. Similar to **DynamicParameters**, the
+available values are calculated at runtime when the user presses <kbd>Tab</kbd>
+after the parameter name.
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompleter-attribute).
+
+## Parameter and variable validation attributes
Validation attributes direct PowerShell to test the parameter values that users submit when they call the advanced function. If the parameter values fail the
test, an error is generated and the function isn't called. Parameter validation
is only applied to the input provided and any other values like default values are not validated.
-You can also use the validation attributes to restrict the values that
-users can specify for variables. When you use a type converter along with a
-validation attribute, the type converter has to be defined before the attribute.
+You can also use the validation attributes to restrict the values that users
+can specify for variables. When you use a type converter along with a
+validation attribute, the type converter has to be defined before the
+attribute.
```powershell [int32][AllowNull()] $number = 7 ```
+> [!NOTE]
+> Validation attributes can be applied to any variable, not just parameters.
+> You can define validation for any variable within a script.
+ ### AllowNull validation attribute The **AllowNull** attribute allows the value of a mandatory parameter to be
parameter that can have an empty string value.
Param( [Parameter(Mandatory=$true)] [AllowEmptyString()]
- [String]
+ [string]
$ComputerName ) ```
parameter to be an empty collection `@()`. The following example declares a
Param( [Parameter(Mandatory=$true)] [AllowEmptyCollection()]
- [String[]]
+ [string[]]
$ComputerName ) ```
takes one to five parameter values.
Param( [Parameter(Mandatory=$true)] [ValidateCount(1,5)]
- [String[]]
+ [string[]]
$ComputerName ) ```
In the following example, each computer name must have one to ten characters.
Param( [Parameter(Mandatory=$true)] [ValidateLength(1,10)]
- [String[]]
+ [string[]]
$ComputerName ) ```
and each digit must be a number zero to nine.
Param( [Parameter(Mandatory=$true)] [ValidatePattern("[0-9][0-9][0-9][0-9]")]
- [String[]]
+ [string[]]
$ComputerName ) ```
High.
Param( [Parameter(Mandatory=$true)] [ValidateSet("Low", "Average", "High")]
- [String[]]
+ [string[]]
$Detail ) ```
Chocolate, Strawberry, or Vanilla.
```powershell [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
-[String]$flavor = "Strawberry"
+[string]$flavor = "Strawberry"
``` The validation occurs whenever that variable is assigned even within the
script. For example, the following results in an error at runtime:
```powershell Param( [ValidateSet("hello", "world")]
- [String]$Message
+ [string]$Message
) $Message = "bye" ```
-#### Dynamic validateSet values
+This example returns the following error at runtime:
+
+```Output
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+Using `ValidateSet` also enable tab expansion of values for that parameter. For
+more information, see [about_Tab_Expansion](about_Tab_Expansion.md).
+
+#### Dynamic ValidateSet values using classes
You can use a **Class** to dynamically generate the values for **ValidateSet** at runtime. In the following example, the valid values for the variable
filesystem paths for available sound files:
```powershell Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
- [String[]] GetValidValues() {
+ [string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/', '/Library/Sounds','~/Library/Sounds' $SoundNames = ForEach ($SoundPath in $SoundPaths) {
Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
(Get-ChildItem $SoundPath).BaseName } }
- return [String[]] $SoundNames
+ return [string[]] $SoundNames
} } ```
as follows:
```powershell Param( [ValidateSet([SoundNames])]
- [String]$Sound
+ [string]$Sound
) ```
empty string (`""`), or an empty array `@()`.
Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
- [String[]]
+ [string[]]
$UserName ) ```
If you use relative path, the current drive must be in the allowed drive list.
```powershell Param( [ValidateDrive("C", "D", "Variable", "Function")]
- [String]$Path
+ [string]$Path
) ```
If you use relative path, the current drive must be `User`.
function Test-UserDrivePath{ [OutputType([bool])] Param(
- [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][String]$Path
+ [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][string]$Path
) $True }
This attribute was added in PowerShell 6.1.1.
At this time, the attribute is used internally by PowerShell itself and is not intended for external usage.
-## Dynamic parameters
-
-Dynamic parameters are parameters of a cmdlet, function, or script that are
-available only under certain conditions.
-
-For example, several provider cmdlets have parameters that are available only
-when the cmdlet is used in the provider drive, or in a particular path of the
-provider drive. For example, the **Encoding** parameter is available on the
-`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
-a file system drive.
-
-You can also create a parameter that appears only when another parameter is
-used in the function command or when another parameter has a certain value.
-
-Dynamic parameters can be useful, but use them only when necessary, because
-they can be difficult for users to discover. To find a dynamic parameter, the
-user must be in the provider path, use the **ArgumentList** parameter of the
-`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
-
-To create a dynamic parameter for a function or script, use the `DynamicParam`
-keyword.
-
-The syntax is as follows:
-
-`DynamicParam {<statement-list>}`
-
-In the statement list, use an `If` statement to specify the conditions under
-which the parameter is available in the function.
-
-Use the `New-Object` cmdlet to create a
-**System.Management.Automation.RuntimeDefinedParameter** object to represent
-the parameter and specify its name.
-
-You can use a `New-Object` command to create a
-**System.Management.Automation.ParameterAttribute** object to represent
-attributes of the parameter, such as **Mandatory**, **Position**, or
-**ValueFromPipeline** or its parameter set.
-
-The following example shows a sample function with standard parameters named
-**Name** and **Path**, and an optional dynamic parameter named **DP1**. The
-**DP1** parameter is in the `PSet1` parameter set and has a type of `Int32`.
-The **DP1** parameter is available in the `Get-Sample` function only when the
-value of the **Path** parameter starts with `HKLM:`, indicating that it's being
-used in the `HKEY_LOCAL_MACHINE` registry drive.
-
-```powershell
-function Get-Sample {
- [CmdletBinding()]
- Param([String]$Name, [String]$Path)
-
- DynamicParam
- {
- if ($Path.StartsWith("HKLM:"))
- {
- $attributes = New-Object -Type `
- System.Management.Automation.ParameterAttribute
- $attributes.ParameterSetName = "PSet1"
- $attributes.Mandatory = $false
- $attributeCollection = New-Object `
- -Type System.Collections.ObjectModel.Collection[System.Attribute]
- $attributeCollection.Add($attributes)
-
- $dynParam1 = New-Object -Type `
- System.Management.Automation.RuntimeDefinedParameter("DP1", [Int32],
- $attributeCollection)
-
- $paramDictionary = New-Object `
- -Type System.Management.Automation.RuntimeDefinedParameterDictionary
- $paramDictionary.Add("DP1", $dynParam1)
- return $paramDictionary
- }
- }
-}
-```
-
-For more information, see
-[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter).
-
-## Switch parameters
-
-Switch parameters are parameters with no parameter value. They're effective
-only when they're used and have only one effect.
-
-For example, the **NoProfile** parameter of **powershell.exe** is a switch
-parameter.
-
-To create a switch parameter in a function, specify the `Switch` type in the
-parameter definition.
-
-For example:
-
-```powershell
-Param([Switch]<ParameterName>)
-```
-
-Or, you can use an another method:
-
-```powershell
-Param(
- [Parameter(Mandatory=$false)]
- [Switch]
- $<ParameterName>
-)
-```
-
-Switch parameters are easy to use and are preferred over Boolean parameters,
-which have a more difficult syntax.
-
-For example, to use a switch parameter, the user types the parameter in the
-command.
-
-`-IncludeAll`
-
-To use a Boolean parameter, the user types the parameter and a Boolean value.
-
-`-IncludeAll:$true`
-
-When creating switch parameters, choose the parameter name carefully. Be sure
-that the parameter name communicates the effect of the parameter to the user.
-Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
-value is required.
-
-## ArgumentCompleter attribute
-
-The **ArgumentCompleter** attribute allows you to add tab completion values to
-a specific parameter. An **ArgumentCompleter** attribute must be defined for
-each parameter that needs tab completion. Similar to **DynamicParameters**, the
-available values are calculated at runtime when the user presses <kbd>Tab</kbd>
-after the parameter name.
-
-To add an **ArgumentCompleter** attribute, you need to define a script block
-that determines the values. The script block must take the following
-parameters in the order specified below. The parameter's names don't matter as
-the values are provided positionally.
-
-The syntax is as follows:
-
-```powershell
-Param(
- [Parameter(Mandatory)]
- [ArgumentCompleter({
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
- # Perform calculation of tab completed values here.
- })]
-)
-```
-
-### ArgumentCompleter script block
-
-The script block parameters are set to the following values:
--- `$commandName` (Position 0) - This parameter is set to the name of the
- command for which the script block is providing tab completion.
-- `$parameterName` (Position 1) - This parameter is set to the parameter whose
- value requires tab completion.
-- `$wordToComplete` (Position 2) - This parameter is set to value the user has
- provided before they pressed <kbd>Tab</kbd>. Your script block should use
- this value to determine tab completion values.
-- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
- Tree (AST) for the current input line. For more information, see
- [Ast Class](/dotnet/api/system.management.automation.language.ast).
-- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
- containing the `$PSBoundParameters` for the cmdlet, before the user pressed
- <kbd>Tab</kbd>. For more information, see
- [about_Automatic_Variables](about_Automatic_Variables.md).
-
-The **ArgumentCompleter** script block must unroll the values using the
-pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
-Returning an array of values causes PowerShell to treat the entire array as
-**one** tab completion value.
-
-The following example adds tab completion to the **Value** parameter. If only
-the **Value** parameter is specified, all possible values, or arguments, for
-**Value** are displayed. When the **Type** parameter is specified, the
-**Value** parameter only displays the possible values for that type.
-
-In addition, the `-like` operator ensures that if the user types the following
-command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
-
-`Test-ArgumentCompleter -Type Fruits -Value A`
-
-```powershell
-function Test-ArgumentCompleter {
-[CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ValidateSet('Fruits', 'Vegetables')]
- $Type,
- [Parameter(Mandatory=$true)]
- [ArgumentCompleter( {
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
-
- $possibleValues = @{
- Fruits = @('Apple', 'Orange', 'Banana')
- Vegetables = @('Tomato', 'Squash', 'Corn')
- }
- if ($fakeBoundParameters.ContainsKey('Type'))
- {
- $possibleValues[$fakeBoundParameters.Type] | Where-Object {
- $_ -like "$wordToComplete*"
- }
- }
- else
- {
- $possibleValues.Values | ForEach-Object {$_}
- }
- } )]
- $Value
- )
-}
-```
-
-## ArgumentCompletions attribute
-
-The **ArgumentCompletions** attribute allows you to add tab completion values
-to a specific parameter. An **ArgumentCompletions** attribute must be defined
-for each parameter that needs tab completion. The **ArgumentCompletions**
-attribute is similar to **ValidateSet**. Both attributes take a list of values
-to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
-However, unlike **ValidateSet**, the values are not validated. Therefore the
-user can supply any value, not just the values in the list.
-
-The **ArgumentCompletions** attribute should not be confused with the
-**ArgumentCompleter** attribute, which needs a scriptblock to define the
-options. the specified values are available
-
-The syntax is as follows:
-
-```powershell
-function Test-ArgumentCompletions {
- [CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ArgumentCompletions('Fruits', 'Vegetables')]
- $Type,
-
- [Parameter()]
- [ArgumentCompletions('Apple', 'Banana', 'Orange')]
- $Fruit,
-
- [Parameter()]
- [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
- $Vegetable
- )
-}
-```
-
-Each of the parameters is provided a list of options to the
-**ArgumentCompletions** attribute to enable tab completion.
-
-This attribute was introduced in PowerShell Core 6.0
- ## See also [about_Automatic_Variables](about_Automatic_Variables.md)
Microsoft.PowerShell.Core About Functions Argument Completion (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Functions_Argument_Completion.md
+---
Last updated : 07/27/2021
+description: Explains the various argument completion options available for function parameters.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_Functions_Argument_Completion?view=powershell-7&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About functions argument completion
+---
+# about_Functions_Argument_Completion
+
+## Short description
+Argument completion is a feature of PowerShell that provide hints, enables
+discovery, and speeds up input entry of argument values.
+
+## Long description
+
+This article describe the different ways you can implement argument completers
+for PowerShell functions. Argument completers provide the possible values for a
+parameter. The available values are calculated at runtime when the user presses
+the <kbd>Tab</kbd> key after the parameter name. There are several ways to
+define an argument completer for a parameter.
+
+> [!NOTE]
+> <kbd>Tab</kbd> is the default key binding on Windows. This keybinding can be
+> changed by the PSReadLine module or the application that is hosting
+> PowerShell. The keybinding is different on non-Windows platforms. For more
+> information, see
+> [about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+## ValidateSet attribute
+
+The **ValidateSet** attribute specifies a set of valid values for a parameter
+or variable and enables tab completion. PowerShell generates an error if a
+parameter or variable value doesn't match a value in the set. In the following
+example, the value of the **Fruit** parameter can only be **Apple**,
+**Banana**, or **Pear**.
+
+```powershell
+Param(
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Apple', 'Banana', 'Pear')]
+ [string[]]
+ $Fruit
+)
+```
+
+In the following example, the value of the variable `$flavor` must be either
+**Chocolate**, **Strawberry**, or **Vanilla**. The `ValidateSet` attribute can
+be used on any variable, not just parameters.
+
+```powershell
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')]
+[string]$flavor = 'Strawberry'
+```
+
+The validation occurs whenever that variable is assigned even within the
+script.
+
+```powershell
+Param(
+ [ValidateSet('hello', 'world')]
+ [string]$Message
+)
+
+$Message = 'bye'
+```
+
+This example returns the following error at runtime:
+
+```
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+For more information about tab expansion, see
+[about_Tab_Expansion](about_Tab_Expansion.md).
+
+### Dynamic ValidateSet values using classes
+
+You can use a **Class** to dynamically generate the values for **ValidateSet**
+at runtime. In the following example, the valid values for the variable
+`$Sound` are generated via a **Class** named **SoundNames** that checks three
+filesystem paths for available sound files:
+
+```powershell
+Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
+ [string[]] GetValidValues() {
+ $SoundPaths = '/System/Library/Sounds/',
+ '/Library/Sounds',
+ '~/Library/Sounds'
+ $SoundNames = ForEach ($SoundPath in $SoundPaths) {
+ If (Test-Path $SoundPath) {
+ (Get-ChildItem $SoundPath).BaseName
+ }
+ }
+ return [string[]] $SoundNames
+ }
+}
+```
+
+The `[SoundNames]` class is then implemented as a dynamic **ValidateSet** value
+as follows:
+
+```powershell
+Param(
+ [ValidateSet([SoundNames])]
+ [string]$Sound
+)
+```
+
+> [!NOTE]
+> The `IValidateSetValuesGenerator` class was introduced in PowerShell 6.0.
+
+## ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated and more like
+suggestions. Therefore the user can supply any value, not just the values in
+the list.
+
+The **ArgumentCompletions** attribute should not be confused with the
+**ArgumentCompleter** attribute, which needs a scriptblock to define the
+options. the specified values are available
+
+The syntax is as follows:
+
+```powershell
+function Test-ArgumentCompletions {
+ [CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompletions('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter()]
+ [ArgumentCompletions('Apple', 'Banana', 'Orange')]
+ $Fruit,
+
+ [Parameter()]
+ [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
+ $Vegetable
+ )
+}
+```
+
+Each of the parameters is provided a list of options to the
+**ArgumentCompletions** attribute to enable tab completion.
+
+This attribute was introduced in PowerShell Core 6.0
+
+## ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion.
+
+To add an **ArgumentCompleter** attribute, you need to define a script block
+that determines the values. The script block must take the following
+parameters in the order specified below. The parameter's names don't matter as
+the values are provided positionally.
+
+The syntax is as follows:
+
+```powershell
+function MyArgumentCompleter {
+ Param(
+ [Parameter(Mandatory)]
+ [ArgumentCompleter( {
+ param ( $commandName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+ # Perform calculation of tab completed values here.
+ } )]
+ $ParamName
+ )
+}
+```
+
+### ArgumentCompleter script block
+
+The script block parameters are set to the following values:
+
+- `$commandName` (Position 0) - This parameter is set to the name of the
+ command for which the script block is providing tab completion.
+- `$parameterName` (Position 1) - This parameter is set to the parameter whose
+ value requires tab completion.
+- `$wordToComplete` (Position 2) - This parameter is set to value the user has
+ provided before they pressed <kbd>Tab</kbd>. Your script block should use
+ this value to determine tab completion values.
+- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
+ Tree (AST) for the current input line. For more information, see the
+ [AST](/dotnet/api/system.management.automation.language.ast) type
+ documentation.
+- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
+ containing the `$PSBoundParameters` for the cmdlet, before the user pressed
+ <kbd>Tab</kbd>. For more information, see
+ [about_Automatic_Variables](about_Automatic_Variables.md).
+
+The **ArgumentCompleter** script block must unroll the values using the
+pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
+Returning an array of values causes PowerShell to treat the entire array as
+**one** tab completion value.
+
+The following example adds tab completion to the **Value** parameter. If only
+the **Value** parameter is specified, all possible values, or arguments, for
+**Value** are displayed. When the **Type** parameter is specified, the
+**Value** parameter only displays the possible values for that type.
+
+In addition, the `-like` operator ensures that if the user types the following
+command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
+
+`Test-ArgumentCompleter -Type Fruits -Value A`
+
+```powershell
+function MyArgumentCompleter{
+ param ( $commaName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+
+ $possibleValues = @{
+ Fruits = @('Apple', 'Orange', 'Banana')
+ Vegetables = @('Tomato', 'Squash', 'Corn')
+ }
+
+ if ($fakeBoundParameters.ContainsKey('Type')) {
+ $possibleValues[$fakeBoundParameters.Type] | Where-Object {
+ $_ -like "$wordToComplete*"
+ }
+ } else {
+ $possibleValues.Values | ForEach-Object {$_}
+ }
+}
+
+function Test-ArgumentCompleter {
+[CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompleter({ MyArgumentCompleter @args })]
+ $Value
+ )
+}
+```
+
+## Register-ArgumentCompleter
+
+The `Register-ArgumentCompleter` cmdlet registers a custom argument completer.
+An argument completer allows you to provide dynamic tab completion, at run time
+for any command that you specify.
+
+For more information, see
+[Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter).
+
+## See also
+
+- [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md)
+- [Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter)
+- [about_Tab_Expansion](about_Tab_Expansion.md)
Microsoft.PowerShell.Core About Remote Requirements (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md
---
-description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
+description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
keywords: powershell,cmdlet Locale: en-US Previously updated : 01/03/2018 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_requirements?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Requirements --- # about_Remote_Requirements
-## SHORT DESCRIPTION
+## Short description
Describes the system requirements and configuration requirements for running remote commands in PowerShell.
-## LONG DESCRIPTION
+## Long description
This topic describes the system requirements, user requirements, and resource requirements for establishing remote connections and running remote commands in PowerShell. It also provides instructions for configuring remote operations.
-Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject,
-Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by
-using Microsoft .NET Framework methods to retrieve the objects. They do not
-use the PowerShell remoting infrastructure. The requirements in this
-document do not apply to these cmdlets.
+> [!NOTE]
+> Many cmdlets (including the `Get-Service`, `Get-Process`, `Get-WMIObject`,
+> `Get-EventLog`, and `Get-WinEvent` cmdlets) get objects from remote computers
+> by using Microsoft .NET Framework methods to retrieve the objects. They do
+> not use the PowerShell remoting infrastructure. The requirements in this
+> document do not apply to these cmdlets.
-To find the cmdlets that have a ComputerName parameter but do not use
-PowerShell remoting, read the description of the ComputerName parameter of the
-cmdlets.
+To find the cmdlets that have a **ComputerName** parameter but do not use
+PowerShell remoting, read the description of the **ComputerName**
+parameter of the cmdlets.
-## SYSTEM REQUIREMENTS
+## System requirements
To run remote sessions on Windows PowerShell 3.0, the local and remote computers must have the following:
PowerShell 3.0, such as the ability to disconnect and reconnect to sessions,
are available only when both computers are running Windows PowerShell 3.0. To find the version number of an installed version of PowerShell,
-use the $PSVersionTable automatic variable.
+use the `$PSVersionTable` automatic variable.
Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are included in Windows 8, Windows Server 2012, and newer releases of the Windows
operating system. WinRM 3.0 is included in Windows Management Framework 3.0
for older operating systems. If the computer does not have the required version of WinRM or the Microsoft .NET Framework, the installation fails.
-## USER PERMISSIONS
+## User permissions
To create remote sessions and run remote commands, by default, the current
-user must be a member of the Administrators group on the remote computer or
+user must be a member of the **Administrators** group on the remote computer or
provide the credentials of an administrator. Otherwise, the command fails. The permissions required to create sessions and run commands on a remote computer (or in a remote session on the local computer) are established by the
-session configuration (also known as an "endpoint") on the remote computer to
+session configuration (also known as an **endpoint**) on the remote computer to
which the session connects. Specifically, the security descriptor on the session configuration determines who has access to the session configuration and who can use it to connect. The security descriptors on the default session configurations,
-Microsoft.PowerShell, Microsoft.PowerShell32, and
-Microsoft.PowerShell.Workflow, allow access only to members of the
-Administrators group.
+**Microsoft.PowerShell**, **Microsoft.PowerShell32**, and
+**Microsoft.PowerShell.Workflow**, allow access only to members of the
+**Administrators** group.
If the current user doesn't have permission to use the session configuration, the command to run a command (which uses a temporary session) or create a
persistent session on the remote computer fails. The user can use the
ConfigurationName parameter of cmdlets that create sessions to select a different session configuration, if one is available.
-Members of the Administrators group on a computer can determine who has
+Members of the **Administrators** group on a computer can determine who has
permission to connect to the computer remotely by changing the security descriptors on the default session configurations and by creating new session configurations with different security descriptors.
configurations with different security descriptors.
For more information about session configurations, see [about_Session_Configurations](about_Session_Configurations.md).
-## WINDOWS NETWORK LOCATIONS
+## Windows network locations
-Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable
+Beginning in Windows PowerShell 3.0, the `Enable-PSRemoting` cmdlet can enable
remoting on client and server versions of Windows on private, domain, and public networks. On server versions of Windows with private and domain networks, the
-Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted remote
+`Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted remote
access. It also creates a firewall rule for public networks that allows remote access only from computers in the same local subnet. This local subnet firewall rule is enabled by default on server versions of Windows on public
-networks, but Enable-PSRemoting reapplies the rule in case it was changed or
+networks, but `Enable-PSRemoting` reapplies the rule in case it was changed or
deleted. On client versions of Windows with private and domain networks, by default,
-the Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted
+the `Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted
remote access. To enable remoting on client versions of Windows with public networks, use the
-SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates
+**SkipNetworkProfileCheck** parameter of the `Enable-PSRemoting` cmdlet. It creates
a firewall rule that allows remote access only from computers in the same local subnet. To remove the local subnet restriction on public networks and allow remote access from all locations on client and server versions of Windows, use the
-Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following
+`Set-NetFirewallRule` cmdlet in the **NetSecurity** module. Run the following
command: ```powershell Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any ```
-In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling the
+> firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+
+In Windows PowerShell 2.0, on server versions of Windows, `Enable-PSRemoting`
creates firewall rules that permit remote access on all networks.
-In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting
+In Windows PowerShell 2.0, on client versions of Windows, `Enable-PSRemoting`
creates firewall rules only on private and domain networks. If the network
-location is public, Enable-PSRemoting fails.
+location is public, `Enable-PSRemoting` fails.
-## RUN AS ADMINISTRATOR
+## Run as administrator
Administrator privileges are required for the following remoting operations:
Administrator privileges are required for the following remoting operations:
the settings in the LocalHost node of the WSMAN: drive. To perform these tasks, you must start PowerShell with the "Run as
-administrator" option even if you are a member of the Administrators group on
+administrator" option even if you are a member of the **Administrators** group on
the local computer.
-In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with
-the "Run as administrator" option:
+In Windows 7 and in Windows Server 2008 R2, to start PowerShell with
+the **Run as administrator** option:
1. Click Start, click All Programs, click Accessories, and then click
- the Windows PowerShell folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+ the PowerShell folder.
+1. Right-click PowerShell, and then click **Run as administrator**.
-To start Windows PowerShell with the "Run as administrator" option:
+To start Windows PowerShell with the **Run as administrator** option:
-1. Click Start, click All Programs, and then click the Windows PowerShell
+1. Click Start, click All Programs, and then click the PowerShell
folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+1. Right-click PowerShell, and then click **Run as administrator**.
-The "Run as administrator" option is also available in other Windows Explorer
-entries for Windows PowerShell, including shortcuts. Just right-click the
-item, and then click "Run as administrator".
+The **Run as administrator** option is also available in other Windows Explorer
+entries for PowerShell, including shortcuts. Just right-click the
+item, and then click **Run as administrator**.
-When you start Windows PowerShell from another program such as Cmd.exe, use
-the "Run as administrator" option to start the program.
+When you start PowerShell from another program such as Cmd.exe, use
+the **Run as administrator** option to start the program.
-## HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING
+## How to configure your computer for remoting
Computers running all supported versions of Windows can establish remote connections to and run remote commands in PowerShell without any
remoting on the computer.
Windows Server 2012 and newer releases of Windows Server are enabled for PowerShell remoting by default. If the settings are changed, you can
-restore the default settings by running the Enable-PSRemoting cmdlet.
+restore the default settings by running the `Enable-PSRemoting` cmdlet.
On all other supported versions of Windows, you need to run the
-Enable-PSRemoting cmdlet to enable PowerShell remoting.
+`Enable-PSRemoting` cmdlet to enable PowerShell remoting.
The remoting features of PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for
configuration that allow users to connect to WS-Management.
To configure PowerShell to receive remote commands:
-1. Start PowerShell with the "Run as administrator" option.
-2. At the command prompt, type: `Enable-PSRemoting`
+1. Start PowerShell with the **Run as administrator** option.
+1. At the command prompt, type: `Enable-PSRemoting`
To verify that remoting is configured correctly, run a test command such as the following command, which creates a remote session on the local computer.
If remoting is configured correctly, the command will create a session on the
local computer and return an object that represents the session. The output should resemble the following sample output:
-```output
+```Output
Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell
Id Name ComputerName State ConfigurationName
If the command fails, for assistance, see [about_Remote_Troubleshooting](about_Remote_Troubleshooting.md).
-## UNDERSTAND POLICIES
+## Understand policies
When you work remotely, you use two instances of PowerShell, one on the local computer and one on the remote computer. As a result, your work is
In general, before you connect and as you are establishing the connection, the
policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect.
-## Basic Authentication Limitations on Linux and macOS
+## Basic authentication limitations on Linux and macOS
When connecting from a Linux or macOS system to Windows, Basic Authentication over HTTP is not supported. Basic Authentication can be used over HTTPS by
winrm create winrm/config/Listener?Address=*+Transport=HTTPS $hostinfo
On the Linux or macOS side, select Basic for authentication and -UseSSl.
-> NOTE: Basic authentication cannot be used with domain accounts; a local account
-is required and the account must be in the Administrators group.
+> [!NOTE]
+> Basic authentication cannot be used with domain accounts; a local account is
+> required and the account must be in the **Administrators** group.
```powershell # The specified local user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
-Authentication Basic -UseSSL ```
-An alternative to Basic Authentication over HTTPS is Negotiate. This results
-in NTLM authentication between the client and server and payload is encrypted
-over HTTP.
+An alternative to **Basic Authentication** over HTTPS is **Negotiate**. This
+results in NTLM authentication between the client and server and payload is
+encrypted over HTTP.
-The following illustrates using Negotiate with New-PSSession:
+The following illustrates using **Negotiate** with `New-PSSession`:
```powershell # The specified user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
> [!NOTE] > Windows Server requires an additional registry setting to enable > administrators, other than the built in administrator, to connect using NTLM.
-> Refer to the LocalAccountTokenFilterPolicy registry setting under Negotiate
-> Authentication in
-> [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
+> Refer to the **LocalAccountTokenFilterPolicy** registry setting under
+> **Negotiate** Authentication in [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
-## SEE ALSO
+## See also
[about_Remote](about_Remote.md)
Microsoft.PowerShell.Core About Remote Troubleshooting (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Remote_Troubleshooting.md
description: Describes how to troubleshoot remote operations in PowerShell. keywords: powershell,cmdlet Locale: en-US Previously updated : 10/27/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Troubleshooting
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
The `Set-NetFirewallRule` cmdlet is exported by the NetSecurity module.
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling
+> the firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+ > [!NOTE] > In Windows PowerShell 2.0, on computers running server versions of Windows, > `Enable-PSRemoting` creates firewall rules that allow remote access on
Microsoft.PowerShell.Core About Tab Expansion (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Tab_Expansion.md
+---
Last updated : 07/27/2021
+description: Explains how to use the Tab Expansion feature in PowerShell.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_tab_expansion?view=powershell-7&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About tab expansion
+---
+# about_Tab_Expansion
+
+## Short description
+PowerShell provides completions on input to provide hints, enable discovery, and
+speed up input entry. Command names, parameter names, argument values and file
+paths can all be completed by pressing the <kbd>Tab</kbd> key.
+
+## Long description
+
+Tab expansion is controlled by the internal function **TabExpansion** or
+**TabExpansion2**. Since this function can be modified or overridden, this
+discussion is a guide to the behavior of the default PowerShell configuration.
+
+The <kbd>Tab</kbd> key is the default key binding on Windows. This keybinding
+can be changed by the PSReadLine module or the application that is hosting
+PowerShell. The keybinding is different on non-Windows platforms. For more
+information, see
+[about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+> [!NOTE]
+> One limitation of the tab expansion process is that tabs are always
+> interpreted as attempts to complete a word. If you copy and paste command
+> examples into a PowerShell console, make sure that the sample does not
+> contain tabs; if it does, the results will be unpredictable and will almost
+> certainly not be what you intended.
+
+## File and cmdlet name completion
+
+To fill in a filename or path from the available choices automatically, type
+part of the name and press the <kbd>Tab</kbd> key. PowerShell will
+automatically expand the name to the first match that it finds. Pressing the
+<kbd>Tab</kbd> key repeatedly will cycle through all of the available choices.
+
+The tab expansion of cmdlet names is slightly different. To use tab expansion
+on a cmdlet name, type the entire first part of the name (the verb) and the
+hyphen that follows it. You can fill in more of the name for a partial match.
+For example, if you type `get-co` and then press the <kbd>Tab</kbd> key,
+PowerShell will automatically expand this to the `Get-Command` cmdlet (notice
+that it also changes the case of letters to their standard form). If you press
+<kbd>Tab</kbd> key again, PowerShell replaces this with the only other matching
+cmdlet name, `Get-Content`.
+
+> [!NOTE]
+> As of PowerShell 7.0, <kbd>Tab</kbd> will also expand abbreviated cmdlets and
+> functions. For example, `i-psdf<tab>` returns `Import-PowerShellDataFile`.
+
+Tab completion also works to resolve PowerShell alias and native executables.
+
+You can use tab expansion repeatedly on the same line. For example, you can use
+tab expansion on the name of the `Get-Content` cmdlet by entering:
+
+### Examples
+
+```
+PS> Get-Con<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content
+```
+
+You can then partially specify the path to the Active Setup log file and use
+tab expansion again:
+
+```
+PS> Get-Content c:\windows\acts<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content C:\windows\actsetup.log
+```
+
+PSReadLine also has a menu completion feature. The default key binding on
+Windows is <kbd>Ctrl</kbd>-<kbd>Space</kbd>.
+
+```
+PS> fore<Ctrl-Space>
+```
+
+When you press <kbd>Ctrl</kbd>-<kbd>Space</kbd>, PowerShell presents the full
+list of matching values as a menu:
+
+```
+PS> foreach
+foreach ForEach-Object foreach.cmd
+```
+
+In this example the string 'fore' is matched to `foreach` (PowerShell alias),
+`ForEach-Object` (cmdlet), and `foreach.cmd` (native command). Use the arrow
+keys to select the value you want.
+
+## Parameter argument completion
+
+Tab completion can also work to complete parameter arguments. This allows you
+to use the <kbd>Tab</kbd> key to cycle through a list of possible values that
+are valid for some parameter.
+
+For more information see,
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md).
+
+## Enumerated value completion
+
+Beginning in PowerShell 7.0, support for tab completion of enums was added. You
+can use tab completion to select the value you want anywhere an enum is used.
+For example:
+
+```
+enum Suits {
+ Clubs = 0
+ Diamonds = 1
+ Hearts = 2
+ Spades = 3
+}
+
+[Suits]$suit = 'c<Tab>
+```
+
+Enumerated values are strings, so the value to be completed must start with a
+single or double-quote character.
+
+When you hit the <kbd>Tab</kbd> key, you get the following results:
+
+```
+[Suits]$suit = 'Clubs'
+```
+
+Tab completion also works with .NET enumerations.
+
+```
+[System.IO.FileAttributes]$attr = 'S<Tab><Tab>
+```
+
+Hitting the <kbd>Tab</kbd> key twice cycles through the two values that start
+with the letter "S". The end result is:
+
+```
+[System.IO.FileAttributes]$attr = 'System'
+```
+
+Beginning in PowerShell 7.0, tab expansion was added for the values of
+`ValidateSet` when assigning to a variable. For example, if you were typing the
+following variable definition:
+
+```
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')][string]$flavor = 'Strawberry'
+$flavor = <tab>
+```
+
+When you hit the <kbd>Tab</kbd> key, you would get the following result:
+
+```
+$flavor = 'Chocolate'
+```
+
+## See also
+
+- [about_Functions_Argument_Completion](about_Functions_Argument_Completion.md)
+- [about_Requires](about_Requires.md)
+- [about_Comment_Based_Help](about_Comment_Based_Help.md)
Microsoft.PowerShell.Core Foreach Object (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/ForEach-Object.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 03/26/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: ForEach-Object
property value type.
### Example 7: Split module names into component names This example shows three ways to split two dot-separated module names into their component names.
+The commands call the **Split** method of strings. The three commands use different syntax, but they
+are equivalent and interchangeable. The output is the same for all three cases.
```powershell "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
PowerShell
Host ```
-The commands call the **Split** method of strings. The three commands use different syntax, but they
-are equivalent and interchangeable.
- The first command uses the traditional syntax, which includes a script block and the current object operator `$_`. It uses the dot syntax to specify the method and parentheses to enclose the delimiter argument. The second command uses the **MemberName** parameter to specify the **Split** method and the
-**ArgumentName** parameter to identify the dot (".") as the split delimiter.
+**ArgumentList** parameter to identify the dot (`.`) as the split delimiter.
The third command uses the **Foreach** alias of the `ForEach-Object` cmdlet and omits the names of the **MemberName** and **ArgumentList** parameters, which are optional.
Microsoft.PowerShell.Core New Pssession (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/New-PSSession.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 12/20/2019 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/new-pssession?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: New-PSSession
New-PSSession [-Name <String[]>] [-ConfigurationName <String>] -ContainerId <Str
### UseWindowsPowerShellParameterSet ```
-New-PSSession [-Name <String[]>] -UseWindowsPowerShell [<CommonParameters>]
+New-PSSession -UseWindowsPowerShell [-Name <string[]>] [<CommonParameters>]
``` ### SSHHost
New-PSSession [-Name <String[]>] [-Port <Int32>] [-HostName] <String[]> [-UserNa
New-PSSession [-Name <String[]>] -SSHConnection <Hashtable[]> [<CommonParameters>] ```
-## DESCRIPTION
+## Description
The `New-PSSession` cmdlet creates a PowerShell session (**PSSession**) on a local or remote computer. When you create a **PSSession**, PowerShell establishes a persistent connection to the
connection information. For more information about how to set up PowerShell SSH
> this if you are in an environment where you can be certain of the server certificate and the > network connection to the target system.
-## EXAMPLES
+## Examples
### Example 1: Create a session on the local computer
This example shows how to create multiple sessions using Secure Shell (SSH) and
contain connection information for each session. Note that this example requires that the target remote computers have SSH configured to support key based user authentication.
-## PARAMETERS
+## Parameters
### -AllowRedirection
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False ```
+### -UseWindowsPowerShell
+
+Creates a remote connection to a new Windows PowerShell runspace on the local system.
+
+```yaml
+Type: System.Management.Automation.SwitchParameter
+Parameter Sets: UseWindowsPowerShellParameterSet
+Aliases:
+
+Required: True
+Position: Named
+Default value: None
+Accept pipeline input: False
+Accept wildcard characters: False
+```
+ ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable,
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable
-WarningAction, and -WarningVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).
-## INPUTS
+## Inputs
### System.String, System.URI, System.Management.Automation.Runspaces.PSSession You can pipe a string, URI, or session object to this cmdlet.
-## OUTPUTS
+## Outputs
### System.Management.Automation.Runspaces.PSSession
-## NOTES
+## Notes
- This cmdlet uses the PowerShell remoting infrastructure. To use this cmdlet, the local computer and any remote computers must be configured for PowerShell remoting. For more
You can pipe a string, URI, or session object to this cmdlet.
more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core).
-## RELATED LINKS
+## Related Links
[Connect-PSSession](Connect-PSSession.md)
Microsoft.PowerShell.Core About Functions Advanced Parameters (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Parameters.md
description: Explains how to add parameters to advanced functions. keywords: powershell,cmdlet Locale: en-US Previously updated : 07/12/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Functions Advanced Parameters
that has the following characteristics:
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
+## Switch parameters
+
+Switch parameters are parameters that take no parameter value.
+Instead, they convey a Boolean true-or-false value through their presence or absence,
+so that when a switch parameter is present it has a **true** value
+and when absent it has a **false** value.
+
+For example, the **Recurse** parameter of `Get-ChildItem` is a switch
+parameter.
+
+To create a switch parameter in a function, specify the `switch` type in the
+parameter definition.
+
+For example, your function may have an option to output data as a byte array:
+
+```powershell
+Param([switch]$AsByteArray)
+```
+
+Switch parameters are easy to use and are preferred over Boolean parameters,
+which have a less natural syntax for PowerShell.
+
+For example, to use a switch parameter, the user types the parameter in the
+command.
+
+`-IncludeAll`
+
+To use a Boolean parameter, the user types the parameter and a Boolean value.
+
+`-IncludeAll $true`
+
+When creating switch parameters, choose the parameter name carefully. Be sure
+that the parameter name communicates the effect of the parameter to the user.
+Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
+value is required.
+
+### Switch parameter design considerations
+
+- Switch parameters should not be given default values. They should always
+ default to false.
+- Switch parameters should be designed so that setting them moves a command
+ from its default functionality to a less common or more complicated mode. The
+ simplest behavior of a command should be the default behavior that does not
+ require the use of switch parameters.
+- Switch parameters should not be mandatory, since that defeats the purpose of
+ a switch; a mandatory switch can only take one value. The only case where is
+ is necessary to make a switch parameter mandatory is when it is needed to
+ differentiate a parameter set. In this case, the switch parameter must be
+ mandatory.
+- Explicitly setting a switch from a boolean can be done with
+ `-MySwitch:$boolValue` and in splatting with
+ `$params = @{ MySwitch = $boolValue }`.
+- Switch parameters are of type `SwitchParameter` but implicitly convert to
+ Boolean. The parameter variable can be used directly in a conditional
+ expression. For example:
+
+ `if ($MySwitch) { ... }`
+
+ There's no need to write `if ($MySwitch.IsPresent) { ... }`
+
+## Dynamic parameters
+
+Dynamic parameters are parameters of a cmdlet, function, or script that are
+available only under certain conditions.
+
+For example, several provider cmdlets have parameters that are available only
+when the cmdlet is used in the provider drive, or in a particular path of the
+provider drive. For example, the **Encoding** parameter is available on the
+`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
+a file system drive.
+
+You can also create a parameter that appears only when another parameter is
+used in the function command or when another parameter has a certain value.
+
+Dynamic parameters can be useful, but use them only when necessary, because
+they can be difficult for users to discover. To find a dynamic parameter, the
+user must be in the provider path, use the **ArgumentList** parameter of the
+`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
+
+To create a dynamic parameter for a function or script, use the `DynamicParam`
+keyword.
+
+The syntax is as follows:
+
+`dynamicparam {<statement-list>}`
+
+In the statement list, use an `if` statement to specify the conditions under
+which the parameter is available in the function.
+
+The following example shows a function with standard parameters named **Name**
+and **Path**, and an optional dynamic parameter named **KeyCount**. The
+**KeyCount** parameter is in the `ByRegistryPath` parameter set and has a type
+of `Int32`. The **KeyCount** parameter is available in the `Get-Sample`
+function only when the value of the **Path** parameter starts with `HKLM:`,
+indicating that it's being used in the `HKEY_LOCAL_MACHINE` registry drive.
+
+```powershell
+function Get-Sample {
+ [CmdletBinding()]
+ Param([string]$Name, [string]$Path)
+
+ DynamicParam
+ {
+ if ($Path.StartsWith("HKLM:"))
+ {
+ $parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
+ ParameterSetName = "ByRegistryPath"
+ Mandatory = $false
+ }
+
+ $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
+ $attributeCollection.Add($parameterAttribute)
+
+ $dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
+ 'KeyCount', [Int32], $attributeCollection
+ )
+
+ $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
+ $paramDictionary.Add('KeyCount', $dynParam1)
+ return $paramDictionary
+ }
+ }
+}
+```
+
+For more information, see the documentation for the
+[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter)
+type.
+ ## Attributes of parameters This section describes the attributes that you can add to function parameters.
The following example declares the **ComputerName** parameter. It uses the
```powershell Param( [Parameter(Mandatory=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
value in the command.
```powershell Param( [Parameter(Position=0)]
- [String[]]
+ [string[]]
$ComputerName ) ```
parameter set, a **UserName** parameter in the `User` parameter set, and a
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false)]
- [Switch]
+ [switch]
$Summary ) ```
the `Computer` parameter set and mandatory in the `User` parameter set.
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false, ParameterSetName="Computer")] [Parameter(Mandatory=$true, ParameterSetName="User")]
- [Switch]
+ [switch]
$Summary ) ```
and accepts an object that's passed to the function from the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
the function through the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
for the function (for example, `.SYNOPSIS`) then this message also shows up in
Param( [Parameter(Mandatory=$true, HelpMessage="Enter one or more computer names separated by commas.")]
- [String[]]
+ [string[]]
$ComputerName ) ```
The following example shows a parameter declaration that adds the **CN** and
Param( [Parameter(Mandatory=$true)] [Alias("CN","MachineName")]
- [String[]]
+ [string[]]
$ComputerName ) ```
for a mandatory **Path** parameter that supports wildcard values.
Param( [Parameter(Mandatory=$true)] [SupportsWildcards()]
- [String[]]
+ [string[]]
$Path ) ```
developer must implement the code to handle the wildcard input. The wildcards
supported can vary according to the underlying API or PowerShell provider. For more information, see [about_Wildcards](about_Wildcards.md).
-### Parameter and variable validation attributes
+## Argument completion attributes
+
+### ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated.
+
+This attribute was introduced in PowerShell Core 6.0
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompletions-attribute).
+
+### ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion. Similar to **DynamicParameters**, the
+available values are calculated at runtime when the user presses <kbd>Tab</kbd>
+after the parameter name.
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompleter-attribute).
+
+## Parameter and variable validation attributes
Validation attributes direct PowerShell to test the parameter values that users submit when they call the advanced function. If the parameter values fail the
test, an error is generated and the function isn't called. Parameter validation
is only applied to the input provided and any other values like default values are not validated.
-You can also use the validation attributes to restrict the values that
-users can specify for variables. When you use a type converter along with a
-validation attribute, the type converter has to be defined before the attribute.
+You can also use the validation attributes to restrict the values that users
+can specify for variables. When you use a type converter along with a
+validation attribute, the type converter has to be defined before the
+attribute.
```powershell [int32][AllowNull()] $number = 7 ```
+> [!NOTE]
+> Validation attributes can be applied to any variable, not just parameters.
+> You can define validation for any variable within a script.
+ ### AllowNull validation attribute The **AllowNull** attribute allows the value of a mandatory parameter to be
parameter that can have an empty string value.
Param( [Parameter(Mandatory=$true)] [AllowEmptyString()]
- [String]
+ [string]
$ComputerName ) ```
parameter to be an empty collection `@()`. The following example declares a
Param( [Parameter(Mandatory=$true)] [AllowEmptyCollection()]
- [String[]]
+ [string[]]
$ComputerName ) ```
takes one to five parameter values.
Param( [Parameter(Mandatory=$true)] [ValidateCount(1,5)]
- [String[]]
+ [string[]]
$ComputerName ) ```
In the following example, each computer name must have one to ten characters.
Param( [Parameter(Mandatory=$true)] [ValidateLength(1,10)]
- [String[]]
+ [string[]]
$ComputerName ) ```
and each digit must be a number zero to nine.
Param( [Parameter(Mandatory=$true)] [ValidatePattern("[0-9][0-9][0-9][0-9]")]
- [String[]]
+ [string[]]
$ComputerName ) ```
High.
Param( [Parameter(Mandatory=$true)] [ValidateSet("Low", "Average", "High")]
- [String[]]
+ [string[]]
$Detail ) ```
Chocolate, Strawberry, or Vanilla.
```powershell [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
-[String]$flavor = "Strawberry"
+[string]$flavor = "Strawberry"
``` The validation occurs whenever that variable is assigned even within the
script. For example, the following results in an error at runtime:
```powershell Param( [ValidateSet("hello", "world")]
- [String]$Message
+ [string]$Message
) $Message = "bye" ```
-#### Dynamic validateSet values
+This example returns the following error at runtime:
+
+```Output
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+Using `ValidateSet` also enable tab expansion of values for that parameter. For
+more information, see [about_Tab_Expansion](about_Tab_Expansion.md).
+
+#### Dynamic ValidateSet values using classes
You can use a **Class** to dynamically generate the values for **ValidateSet** at runtime. In the following example, the valid values for the variable
filesystem paths for available sound files:
```powershell Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
- [String[]] GetValidValues() {
+ [string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/', '/Library/Sounds','~/Library/Sounds' $SoundNames = ForEach ($SoundPath in $SoundPaths) {
Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
(Get-ChildItem $SoundPath).BaseName } }
- return [String[]] $SoundNames
+ return [string[]] $SoundNames
} } ```
as follows:
```powershell Param( [ValidateSet([SoundNames])]
- [String]$Sound
+ [string]$Sound
) ```
empty string (`""`), or an empty array `@()`.
Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
- [String[]]
+ [string[]]
$UserName ) ```
If you use relative path, the current drive must be in the allowed drive list.
```powershell Param( [ValidateDrive("C", "D", "Variable", "Function")]
- [String]$Path
+ [string]$Path
) ```
If you use relative path, the current drive must be `User`.
function Test-UserDrivePath{ [OutputType([bool])] Param(
- [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][String]$Path
+ [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][string]$Path
) $True }
This attribute was added in PowerShell 6.1.1.
At this time, the attribute is used internally by PowerShell itself and is not intended for external usage.
-## Dynamic parameters
-
-Dynamic parameters are parameters of a cmdlet, function, or script that are
-available only under certain conditions.
-
-For example, several provider cmdlets have parameters that are available only
-when the cmdlet is used in the provider drive, or in a particular path of the
-provider drive. For example, the **Encoding** parameter is available on the
-`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
-a file system drive.
-
-You can also create a parameter that appears only when another parameter is
-used in the function command or when another parameter has a certain value.
-
-Dynamic parameters can be useful, but use them only when necessary, because
-they can be difficult for users to discover. To find a dynamic parameter, the
-user must be in the provider path, use the **ArgumentList** parameter of the
-`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
-
-To create a dynamic parameter for a function or script, use the `DynamicParam`
-keyword.
-
-The syntax is as follows:
-
-`DynamicParam {<statement-list>}`
-
-In the statement list, use an `If` statement to specify the conditions under
-which the parameter is available in the function.
-
-Use the `New-Object` cmdlet to create a
-**System.Management.Automation.RuntimeDefinedParameter** object to represent
-the parameter and specify its name.
-
-You can use a `New-Object` command to create a
-**System.Management.Automation.ParameterAttribute** object to represent
-attributes of the parameter, such as **Mandatory**, **Position**, or
-**ValueFromPipeline** or its parameter set.
-
-The following example shows a sample function with standard parameters named
-**Name** and **Path**, and an optional dynamic parameter named **DP1**. The
-**DP1** parameter is in the `PSet1` parameter set and has a type of `Int32`.
-The **DP1** parameter is available in the `Get-Sample` function only when the
-value of the **Path** parameter starts with `HKLM:`, indicating that it's being
-used in the `HKEY_LOCAL_MACHINE` registry drive.
-
-```powershell
-function Get-Sample {
- [CmdletBinding()]
- Param([String]$Name, [String]$Path)
-
- DynamicParam
- {
- if ($Path.StartsWith("HKLM:"))
- {
- $attributes = New-Object -Type `
- System.Management.Automation.ParameterAttribute
- $attributes.ParameterSetName = "PSet1"
- $attributes.Mandatory = $false
- $attributeCollection = New-Object `
- -Type System.Collections.ObjectModel.Collection[System.Attribute]
- $attributeCollection.Add($attributes)
-
- $dynParam1 = New-Object -Type `
- System.Management.Automation.RuntimeDefinedParameter("DP1", [Int32],
- $attributeCollection)
-
- $paramDictionary = New-Object `
- -Type System.Management.Automation.RuntimeDefinedParameterDictionary
- $paramDictionary.Add("DP1", $dynParam1)
- return $paramDictionary
- }
- }
-}
-```
-
-For more information, see
-[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter).
-
-## Switch parameters
-
-Switch parameters are parameters with no parameter value. They're effective
-only when they're used and have only one effect.
-
-For example, the **NoProfile** parameter of **powershell.exe** is a switch
-parameter.
-
-To create a switch parameter in a function, specify the `Switch` type in the
-parameter definition.
-
-For example:
-
-```powershell
-Param([Switch]<ParameterName>)
-```
-
-Or, you can use an another method:
-
-```powershell
-Param(
- [Parameter(Mandatory=$false)]
- [Switch]
- $<ParameterName>
-)
-```
-
-Switch parameters are easy to use and are preferred over Boolean parameters,
-which have a more difficult syntax.
-
-For example, to use a switch parameter, the user types the parameter in the
-command.
-
-`-IncludeAll`
-
-To use a Boolean parameter, the user types the parameter and a Boolean value.
-
-`-IncludeAll:$true`
-
-When creating switch parameters, choose the parameter name carefully. Be sure
-that the parameter name communicates the effect of the parameter to the user.
-Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
-value is required.
-
-## ArgumentCompleter attribute
-
-The **ArgumentCompleter** attribute allows you to add tab completion values to
-a specific parameter. An **ArgumentCompleter** attribute must be defined for
-each parameter that needs tab completion. Similar to **DynamicParameters**, the
-available values are calculated at runtime when the user presses <kbd>Tab</kbd>
-after the parameter name.
-
-To add an **ArgumentCompleter** attribute, you need to define a script block
-that determines the values. The script block must take the following
-parameters in the order specified below. The parameter's names don't matter as
-the values are provided positionally.
-
-The syntax is as follows:
-
-```powershell
-Param(
- [Parameter(Mandatory)]
- [ArgumentCompleter({
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
- # Perform calculation of tab completed values here.
- })]
-)
-```
-
-### ArgumentCompleter script block
-
-The script block parameters are set to the following values:
--- `$commandName` (Position 0) - This parameter is set to the name of the
- command for which the script block is providing tab completion.
-- `$parameterName` (Position 1) - This parameter is set to the parameter whose
- value requires tab completion.
-- `$wordToComplete` (Position 2) - This parameter is set to value the user has
- provided before they pressed <kbd>Tab</kbd>. Your script block should use
- this value to determine tab completion values.
-- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
- Tree (AST) for the current input line. For more information, see
- [Ast Class](/dotnet/api/system.management.automation.language.ast).
-- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
- containing the `$PSBoundParameters` for the cmdlet, before the user pressed
- <kbd>Tab</kbd>. For more information, see
- [about_Automatic_Variables](about_Automatic_Variables.md).
-
-The **ArgumentCompleter** script block must unroll the values using the
-pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
-Returning an array of values causes PowerShell to treat the entire array as
-**one** tab completion value.
-
-The following example adds tab completion to the **Value** parameter. If only
-the **Value** parameter is specified, all possible values, or arguments, for
-**Value** are displayed. When the **Type** parameter is specified, the
-**Value** parameter only displays the possible values for that type.
-
-In addition, the `-like` operator ensures that if the user types the following
-command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
-
-`Test-ArgumentCompleter -Type Fruits -Value A`
-
-```powershell
-function Test-ArgumentCompleter {
-[CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ValidateSet('Fruits', 'Vegetables')]
- $Type,
- [Parameter(Mandatory=$true)]
- [ArgumentCompleter( {
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
-
- $possibleValues = @{
- Fruits = @('Apple', 'Orange', 'Banana')
- Vegetables = @('Tomato', 'Squash', 'Corn')
- }
- if ($fakeBoundParameters.ContainsKey('Type'))
- {
- $possibleValues[$fakeBoundParameters.Type] | Where-Object {
- $_ -like "$wordToComplete*"
- }
- }
- else
- {
- $possibleValues.Values | ForEach-Object {$_}
- }
- } )]
- $Value
- )
-}
-```
-
-## ArgumentCompletions attribute
-
-The **ArgumentCompletions** attribute allows you to add tab completion values
-to a specific parameter. An **ArgumentCompletions** attribute must be defined
-for each parameter that needs tab completion. The **ArgumentCompletions**
-attribute is similar to **ValidateSet**. Both attributes take a list of values
-to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
-However, unlike **ValidateSet**, the values are not validated. Therefore the
-user can supply any value, not just the values in the list.
-
-The **ArgumentCompletions** attribute should not be confused with the
-**ArgumentCompleter** attribute, which needs a scriptblock to define the
-options. the specified values are available
-
-The syntax is as follows:
-
-```powershell
-function Test-ArgumentCompletions {
- [CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ArgumentCompletions('Fruits', 'Vegetables')]
- $Type,
-
- [Parameter()]
- [ArgumentCompletions('Apple', 'Banana', 'Orange')]
- $Fruit,
-
- [Parameter()]
- [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
- $Vegetable
- )
-}
-```
-
-Each of the parameters is provided a list of options to the
-**ArgumentCompletions** attribute to enable tab completion.
-
-This attribute was introduced in PowerShell Core 6.0
- ## See also [about_Automatic_Variables](about_Automatic_Variables.md)
Microsoft.PowerShell.Core About Functions Argument Completion (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Functions_Argument_Completion.md
+---
Last updated : 07/27/2021
+description: Explains the various argument completion options available for function parameters.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_argument_completion?view=powershell-7.1&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About functions argument completion
+---
+# about_Functions_Argument_Completion
+
+## Short description
+Argument completion is a feature of PowerShell that provide hints, enables
+discovery, and speeds up input entry of argument values.
+
+## Long description
+
+This article describe the different ways you can implement argument completers
+for PowerShell functions. Argument completers provide the possible values for a
+parameter. The available values are calculated at runtime when the user presses
+the <kbd>Tab</kbd> key after the parameter name. There are several ways to
+define an argument completer for a parameter.
+
+> [!NOTE]
+> <kbd>Tab</kbd> is the default key binding on Windows. This keybinding can be
+> changed by the PSReadLine module or the application that is hosting
+> PowerShell. The keybinding is different on non-Windows platforms. For more
+> information, see
+> [about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+## ValidateSet attribute
+
+The **ValidateSet** attribute specifies a set of valid values for a parameter
+or variable and enables tab completion. PowerShell generates an error if a
+parameter or variable value doesn't match a value in the set. In the following
+example, the value of the **Fruit** parameter can only be **Apple**,
+**Banana**, or **Pear**.
+
+```powershell
+Param(
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Apple', 'Banana', 'Pear')]
+ [string[]]
+ $Fruit
+)
+```
+
+In the following example, the value of the variable `$flavor` must be either
+**Chocolate**, **Strawberry**, or **Vanilla**. The `ValidateSet` attribute can
+be used on any variable, not just parameters.
+
+```powershell
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')]
+[string]$flavor = 'Strawberry'
+```
+
+The validation occurs whenever that variable is assigned even within the
+script.
+
+```powershell
+Param(
+ [ValidateSet('hello', 'world')]
+ [string]$Message
+)
+
+$Message = 'bye'
+```
+
+This example returns the following error at runtime:
+
+```
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+For more information about tab expansion, see
+[about_Tab_Expansion](about_Tab_Expansion.md).
+
+### Dynamic ValidateSet values using classes
+
+You can use a **Class** to dynamically generate the values for **ValidateSet**
+at runtime. In the following example, the valid values for the variable
+`$Sound` are generated via a **Class** named **SoundNames** that checks three
+filesystem paths for available sound files:
+
+```powershell
+Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
+ [string[]] GetValidValues() {
+ $SoundPaths = '/System/Library/Sounds/',
+ '/Library/Sounds',
+ '~/Library/Sounds'
+ $SoundNames = ForEach ($SoundPath in $SoundPaths) {
+ If (Test-Path $SoundPath) {
+ (Get-ChildItem $SoundPath).BaseName
+ }
+ }
+ return [string[]] $SoundNames
+ }
+}
+```
+
+The `[SoundNames]` class is then implemented as a dynamic **ValidateSet** value
+as follows:
+
+```powershell
+Param(
+ [ValidateSet([SoundNames])]
+ [string]$Sound
+)
+```
+
+> [!NOTE]
+> The `IValidateSetValuesGenerator` class was introduced in PowerShell 6.0.
+
+## ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated and more like
+suggestions. Therefore the user can supply any value, not just the values in
+the list.
+
+The **ArgumentCompletions** attribute should not be confused with the
+**ArgumentCompleter** attribute, which needs a scriptblock to define the
+options. the specified values are available
+
+The syntax is as follows:
+
+```powershell
+function Test-ArgumentCompletions {
+ [CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompletions('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter()]
+ [ArgumentCompletions('Apple', 'Banana', 'Orange')]
+ $Fruit,
+
+ [Parameter()]
+ [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
+ $Vegetable
+ )
+}
+```
+
+Each of the parameters is provided a list of options to the
+**ArgumentCompletions** attribute to enable tab completion.
+
+This attribute was introduced in PowerShell Core 6.0
+
+## ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion.
+
+To add an **ArgumentCompleter** attribute, you need to define a script block
+that determines the values. The script block must take the following
+parameters in the order specified below. The parameter's names don't matter as
+the values are provided positionally.
+
+The syntax is as follows:
+
+```powershell
+function MyArgumentCompleter {
+ Param(
+ [Parameter(Mandatory)]
+ [ArgumentCompleter( {
+ param ( $commandName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+ # Perform calculation of tab completed values here.
+ } )]
+ $ParamName
+ )
+}
+```
+
+### ArgumentCompleter script block
+
+The script block parameters are set to the following values:
+
+- `$commandName` (Position 0) - This parameter is set to the name of the
+ command for which the script block is providing tab completion.
+- `$parameterName` (Position 1) - This parameter is set to the parameter whose
+ value requires tab completion.
+- `$wordToComplete` (Position 2) - This parameter is set to value the user has
+ provided before they pressed <kbd>Tab</kbd>. Your script block should use
+ this value to determine tab completion values.
+- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
+ Tree (AST) for the current input line. For more information, see the
+ [AST](/dotnet/api/system.management.automation.language.ast) type
+ documentation.
+- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
+ containing the `$PSBoundParameters` for the cmdlet, before the user pressed
+ <kbd>Tab</kbd>. For more information, see
+ [about_Automatic_Variables](about_Automatic_Variables.md).
+
+The **ArgumentCompleter** script block must unroll the values using the
+pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
+Returning an array of values causes PowerShell to treat the entire array as
+**one** tab completion value.
+
+The following example adds tab completion to the **Value** parameter. If only
+the **Value** parameter is specified, all possible values, or arguments, for
+**Value** are displayed. When the **Type** parameter is specified, the
+**Value** parameter only displays the possible values for that type.
+
+In addition, the `-like` operator ensures that if the user types the following
+command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
+
+`Test-ArgumentCompleter -Type Fruits -Value A`
+
+```powershell
+function MyArgumentCompleter{
+ param ( $commaName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+
+ $possibleValues = @{
+ Fruits = @('Apple', 'Orange', 'Banana')
+ Vegetables = @('Tomato', 'Squash', 'Corn')
+ }
+
+ if ($fakeBoundParameters.ContainsKey('Type')) {
+ $possibleValues[$fakeBoundParameters.Type] | Where-Object {
+ $_ -like "$wordToComplete*"
+ }
+ } else {
+ $possibleValues.Values | ForEach-Object {$_}
+ }
+}
+
+function Test-ArgumentCompleter {
+[CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompleter({ MyArgumentCompleter @args })]
+ $Value
+ )
+}
+```
+
+## Register-ArgumentCompleter
+
+The `Register-ArgumentCompleter` cmdlet registers a custom argument completer.
+An argument completer allows you to provide dynamic tab completion, at run time
+for any command that you specify.
+
+For more information, see
+[Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter).
+
+## See also
+
+- [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md)
+- [Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter)
+- [about_Tab_Expansion](about_Tab_Expansion.md)
Microsoft.PowerShell.Core About Remote Requirements (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md
---
-description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
+description: Describes the system requirements and configuration requirements for running remote commands in PowerShell.
keywords: powershell,cmdlet Locale: en-US Previously updated : 01/03/2018 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_requirements?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Requirements --- # about_Remote_Requirements
-## SHORT DESCRIPTION
+## Short description
Describes the system requirements and configuration requirements for running remote commands in PowerShell.
-## LONG DESCRIPTION
+## Long description
This topic describes the system requirements, user requirements, and resource requirements for establishing remote connections and running remote commands in PowerShell. It also provides instructions for configuring remote operations.
-Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject,
-Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by
-using Microsoft .NET Framework methods to retrieve the objects. They do not
-use the PowerShell remoting infrastructure. The requirements in this
-document do not apply to these cmdlets.
+> [!NOTE]
+> Many cmdlets (including the `Get-Service`, `Get-Process`, `Get-WMIObject`,
+> `Get-EventLog`, and `Get-WinEvent` cmdlets) get objects from remote computers
+> by using Microsoft .NET Framework methods to retrieve the objects. They do
+> not use the PowerShell remoting infrastructure. The requirements in this
+> document do not apply to these cmdlets.
-To find the cmdlets that have a ComputerName parameter but do not use
-PowerShell remoting, read the description of the ComputerName parameter of the
-cmdlets.
+To find the cmdlets that have a **ComputerName** parameter but do not use
+PowerShell remoting, read the description of the **ComputerName**
+parameter of the cmdlets.
-## SYSTEM REQUIREMENTS
+## System requirements
To run remote sessions on Windows PowerShell 3.0, the local and remote computers must have the following:
PowerShell 3.0, such as the ability to disconnect and reconnect to sessions,
are available only when both computers are running Windows PowerShell 3.0. To find the version number of an installed version of PowerShell,
-use the $PSVersionTable automatic variable.
+use the `$PSVersionTable` automatic variable.
Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are included in Windows 8, Windows Server 2012, and newer releases of the Windows
operating system. WinRM 3.0 is included in Windows Management Framework 3.0
for older operating systems. If the computer does not have the required version of WinRM or the Microsoft .NET Framework, the installation fails.
-## USER PERMISSIONS
+## User permissions
To create remote sessions and run remote commands, by default, the current
-user must be a member of the Administrators group on the remote computer or
+user must be a member of the **Administrators** group on the remote computer or
provide the credentials of an administrator. Otherwise, the command fails. The permissions required to create sessions and run commands on a remote computer (or in a remote session on the local computer) are established by the
-session configuration (also known as an "endpoint") on the remote computer to
+session configuration (also known as an **endpoint**) on the remote computer to
which the session connects. Specifically, the security descriptor on the session configuration determines who has access to the session configuration and who can use it to connect. The security descriptors on the default session configurations,
-Microsoft.PowerShell, Microsoft.PowerShell32, and
-Microsoft.PowerShell.Workflow, allow access only to members of the
-Administrators group.
+**Microsoft.PowerShell**, **Microsoft.PowerShell32**, and
+**Microsoft.PowerShell.Workflow**, allow access only to members of the
+**Administrators** group.
If the current user doesn't have permission to use the session configuration, the command to run a command (which uses a temporary session) or create a
persistent session on the remote computer fails. The user can use the
ConfigurationName parameter of cmdlets that create sessions to select a different session configuration, if one is available.
-Members of the Administrators group on a computer can determine who has
+Members of the **Administrators** group on a computer can determine who has
permission to connect to the computer remotely by changing the security descriptors on the default session configurations and by creating new session configurations with different security descriptors.
configurations with different security descriptors.
For more information about session configurations, see [about_Session_Configurations](about_Session_Configurations.md).
-## WINDOWS NETWORK LOCATIONS
+## Windows network locations
-Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable
+Beginning in Windows PowerShell 3.0, the `Enable-PSRemoting` cmdlet can enable
remoting on client and server versions of Windows on private, domain, and public networks. On server versions of Windows with private and domain networks, the
-Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted remote
+`Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted remote
access. It also creates a firewall rule for public networks that allows remote access only from computers in the same local subnet. This local subnet firewall rule is enabled by default on server versions of Windows on public
-networks, but Enable-PSRemoting reapplies the rule in case it was changed or
+networks, but `Enable-PSRemoting` reapplies the rule in case it was changed or
deleted. On client versions of Windows with private and domain networks, by default,
-the Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted
+the `Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted
remote access. To enable remoting on client versions of Windows with public networks, use the
-SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates
+**SkipNetworkProfileCheck** parameter of the `Enable-PSRemoting` cmdlet. It creates
a firewall rule that allows remote access only from computers in the same local subnet. To remove the local subnet restriction on public networks and allow remote access from all locations on client and server versions of Windows, use the
-Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following
+`Set-NetFirewallRule` cmdlet in the **NetSecurity** module. Run the following
command: ```powershell Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any ```
-In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling the
+> firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+
+In Windows PowerShell 2.0, on server versions of Windows, `Enable-PSRemoting`
creates firewall rules that permit remote access on all networks.
-In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting
+In Windows PowerShell 2.0, on client versions of Windows, `Enable-PSRemoting`
creates firewall rules only on private and domain networks. If the network
-location is public, Enable-PSRemoting fails.
+location is public, `Enable-PSRemoting` fails.
-## RUN AS ADMINISTRATOR
+## Run as administrator
Administrator privileges are required for the following remoting operations:
Administrator privileges are required for the following remoting operations:
the settings in the LocalHost node of the WSMAN: drive. To perform these tasks, you must start PowerShell with the "Run as
-administrator" option even if you are a member of the Administrators group on
+administrator" option even if you are a member of the **Administrators** group on
the local computer.
-In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with
-the "Run as administrator" option:
+In Windows 7 and in Windows Server 2008 R2, to start PowerShell with
+the **Run as administrator** option:
1. Click Start, click All Programs, click Accessories, and then click
- the Windows PowerShell folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+ the PowerShell folder.
+1. Right-click PowerShell, and then click **Run as administrator**.
-To start Windows PowerShell with the "Run as administrator" option:
+To start Windows PowerShell with the **Run as administrator** option:
-1. Click Start, click All Programs, and then click the Windows PowerShell
+1. Click Start, click All Programs, and then click the PowerShell
folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+1. Right-click PowerShell, and then click **Run as administrator**.
-The "Run as administrator" option is also available in other Windows Explorer
-entries for Windows PowerShell, including shortcuts. Just right-click the
-item, and then click "Run as administrator".
+The **Run as administrator** option is also available in other Windows Explorer
+entries for PowerShell, including shortcuts. Just right-click the
+item, and then click **Run as administrator**.
-When you start Windows PowerShell from another program such as Cmd.exe, use
-the "Run as administrator" option to start the program.
+When you start PowerShell from another program such as Cmd.exe, use
+the **Run as administrator** option to start the program.
-## HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING
+## How to configure your computer for remoting
Computers running all supported versions of Windows can establish remote connections to and run remote commands in PowerShell without any
remoting on the computer.
Windows Server 2012 and newer releases of Windows Server are enabled for PowerShell remoting by default. If the settings are changed, you can
-restore the default settings by running the Enable-PSRemoting cmdlet.
+restore the default settings by running the `Enable-PSRemoting` cmdlet.
On all other supported versions of Windows, you need to run the
-Enable-PSRemoting cmdlet to enable PowerShell remoting.
+`Enable-PSRemoting` cmdlet to enable PowerShell remoting.
The remoting features of PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for
configuration that allow users to connect to WS-Management.
To configure PowerShell to receive remote commands:
-1. Start PowerShell with the "Run as administrator" option.
-2. At the command prompt, type: `Enable-PSRemoting`
+1. Start PowerShell with the **Run as administrator** option.
+1. At the command prompt, type: `Enable-PSRemoting`
To verify that remoting is configured correctly, run a test command such as the following command, which creates a remote session on the local computer.
If remoting is configured correctly, the command will create a session on the
local computer and return an object that represents the session. The output should resemble the following sample output:
-```output
+```Output
Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell
Id Name ComputerName State ConfigurationName
If the command fails, for assistance, see [about_Remote_Troubleshooting](about_Remote_Troubleshooting.md).
-## UNDERSTAND POLICIES
+## Understand policies
When you work remotely, you use two instances of PowerShell, one on the local computer and one on the remote computer. As a result, your work is
In general, before you connect and as you are establishing the connection, the
policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect.
-## Basic Authentication Limitations on Linux and macOS
+## Basic authentication limitations on Linux and macOS
When connecting from a Linux or macOS system to Windows, Basic Authentication over HTTP is not supported. Basic Authentication can be used over HTTPS by
winrm create winrm/config/Listener?Address=*+Transport=HTTPS $hostinfo
On the Linux or macOS side, select Basic for authentication and -UseSSl.
-> NOTE: Basic authentication cannot be used with domain accounts; a local account
-is required and the account must be in the Administrators group.
+> [!NOTE]
+> Basic authentication cannot be used with domain accounts; a local account is
+> required and the account must be in the **Administrators** group.
```powershell # The specified local user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
-Authentication Basic -UseSSL ```
-An alternative to Basic Authentication over HTTPS is Negotiate. This results
-in NTLM authentication between the client and server and payload is encrypted
-over HTTP.
+An alternative to **Basic Authentication** over HTTPS is **Negotiate**. This
+results in NTLM authentication between the client and server and payload is
+encrypted over HTTP.
-The following illustrates using Negotiate with New-PSSession:
+The following illustrates using **Negotiate** with `New-PSSession`:
```powershell # The specified user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
> [!NOTE] > Windows Server requires an additional registry setting to enable > administrators, other than the built in administrator, to connect using NTLM.
-> Refer to the LocalAccountTokenFilterPolicy registry setting under Negotiate
-> Authentication in
-> [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
+> Refer to the **LocalAccountTokenFilterPolicy** registry setting under
+> **Negotiate** Authentication in [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
-## SEE ALSO
+## See also
[about_Remote](about_Remote.md)
$session = New-PSSession -Computer <hostname> -Credential $cred `
[Enter-PSSession](xref:Microsoft.PowerShell.Core.Enter-PSSession) [New-PSSession](xref:Microsoft.PowerShell.Core.New-PSSession)-
Microsoft.PowerShell.Core About Remote Troubleshooting (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Remote_Troubleshooting.md
description: Describes how to troubleshoot remote operations in PowerShell. keywords: powershell,cmdlet Locale: en-US Previously updated : 10/27/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Troubleshooting
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
The `Set-NetFirewallRule` cmdlet is exported by the NetSecurity module.
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling
+> the firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+ > [!NOTE] > In Windows PowerShell 2.0, on computers running server versions of Windows, > `Enable-PSRemoting` creates firewall rules that allow remote access on
Microsoft.PowerShell.Core About Tab Expansion (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Tab_Expansion.md
+---
Last updated : 07/27/2021
+description: Explains how to use the Tab Expansion feature in PowerShell.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_tab_expansion?view=powershell-7.1&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About tab expansion
+---
+# about_Tab_Expansion
+
+## Short description
+PowerShell provides completions on input to provide hints, enable discovery, and
+speed up input entry. Command names, parameter names, argument values and file
+paths can all be completed by pressing the <kbd>Tab</kbd> key.
+
+## Long description
+
+Tab expansion is controlled by the internal function **TabExpansion** or
+**TabExpansion2**. Since this function can be modified or overridden, this
+discussion is a guide to the behavior of the default PowerShell configuration.
+
+The <kbd>Tab</kbd> key is the default key binding on Windows. This keybinding
+can be changed by the PSReadLine module or the application that is hosting
+PowerShell. The keybinding is different on non-Windows platforms. For more
+information, see
+[about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+> [!NOTE]
+> One limitation of the tab expansion process is that tabs are always
+> interpreted as attempts to complete a word. If you copy and paste command
+> examples into a PowerShell console, make sure that the sample does not
+> contain tabs; if it does, the results will be unpredictable and will almost
+> certainly not be what you intended.
+
+## File and cmdlet name completion
+
+To fill in a filename or path from the available choices automatically, type
+part of the name and press the <kbd>Tab</kbd> key. PowerShell will
+automatically expand the name to the first match that it finds. Pressing the
+<kbd>Tab</kbd> key repeatedly will cycle through all of the available choices.
+
+The tab expansion of cmdlet names is slightly different. To use tab expansion
+on a cmdlet name, type the entire first part of the name (the verb) and the
+hyphen that follows it. You can fill in more of the name for a partial match.
+For example, if you type `get-co` and then press the <kbd>Tab</kbd> key,
+PowerShell will automatically expand this to the `Get-Command` cmdlet (notice
+that it also changes the case of letters to their standard form). If you press
+<kbd>Tab</kbd> key again, PowerShell replaces this with the only other matching
+cmdlet name, `Get-Content`.
+
+> [!NOTE]
+> As of PowerShell 7.0, <kbd>Tab</kbd> will also expand abbreviated cmdlets and
+> functions. For example, `i-psdf<tab>` returns `Import-PowerShellDataFile`.
+
+Tab completion also works to resolve PowerShell alias and native executables.
+
+You can use tab expansion repeatedly on the same line. For example, you can use
+tab expansion on the name of the `Get-Content` cmdlet by entering:
+
+### Examples
+
+```
+PS> Get-Con<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content
+```
+
+You can then partially specify the path to the Active Setup log file and use
+tab expansion again:
+
+```
+PS> Get-Content c:\windows\acts<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content C:\windows\actsetup.log
+```
+
+PSReadLine also has a menu completion feature. The default key binding on
+Windows is <kbd>Ctrl</kbd>-<kbd>Space</kbd>.
+
+```
+PS> fore<Ctrl-Space>
+```
+
+When you press <kbd>Ctrl</kbd>-<kbd>Space</kbd>, PowerShell presents the full
+list of matching values as a menu:
+
+```
+PS> foreach
+foreach ForEach-Object foreach.cmd
+```
+
+In this example the string 'fore' is matched to `foreach` (PowerShell alias),
+`ForEach-Object` (cmdlet), and `foreach.cmd` (native command). Use the arrow
+keys to select the value you want.
+
+## Parameter argument completion
+
+Tab completion can also work to complete parameter arguments. This allows you
+to use the <kbd>Tab</kbd> key to cycle through a list of possible values that
+are valid for some parameter.
+
+For more information see,
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md).
+
+## Enumerated value completion
+
+Beginning in PowerShell 7.0, support for tab completion of enums was added. You
+can use tab completion to select the value you want anywhere an enum is used.
+For example:
+
+```
+enum Suits {
+ Clubs = 0
+ Diamonds = 1
+ Hearts = 2
+ Spades = 3
+}
+
+[Suits]$suit = 'c<Tab>
+```
+
+Enumerated values are strings, so the value to be completed must start with a
+single or double-quote character.
+
+When you hit the <kbd>Tab</kbd> key, you get the following results:
+
+```
+[Suits]$suit = 'Clubs'
+```
+
+Tab completion also works with .NET enumerations.
+
+```
+[System.IO.FileAttributes]$attr = 'S<Tab><Tab>
+```
+
+Hitting the <kbd>Tab</kbd> key twice cycles through the two values that start
+with the letter "S". The end result is:
+
+```
+[System.IO.FileAttributes]$attr = 'System'
+```
+
+Beginning in PowerShell 7.0, tab expansion was added for the values of
+`ValidateSet` when assigning to a variable. For example, if you were typing the
+following variable definition:
+
+```
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')][string]$flavor = 'Strawberry'
+$flavor = <tab>
+```
+
+When you hit the <kbd>Tab</kbd> key, you would get the following result:
+
+```
+$flavor = 'Chocolate'
+```
+
+## See also
+
+- [about_Functions_Argument_Completion](about_Functions_Argument_Completion.md)
+- [about_Requires](about_Requires.md)
+- [about_Comment_Based_Help](about_Comment_Based_Help.md)
Microsoft.PowerShell.Core Foreach Object (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/ForEach-Object.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 03/26/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: ForEach-Object
property value type.
### Example 7: Split module names into component names This example shows three ways to split two dot-separated module names into their component names.
+The commands call the **Split** method of strings. The three commands use different syntax, but they
+are equivalent and interchangeable. The output is the same for all three cases.
```powershell "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
PowerShell
Host ```
-The commands call the **Split** method of strings. The three commands use different syntax, but they
-are equivalent and interchangeable.
- The first command uses the traditional syntax, which includes a script block and the current object operator `$_`. It uses the dot syntax to specify the method and parentheses to enclose the delimiter argument. The second command uses the **MemberName** parameter to specify the **Split** method and the
-**ArgumentName** parameter to identify the dot (".") as the split delimiter.
+**ArgumentList** parameter to identify the dot (`.`) as the split delimiter.
The third command uses the **Foreach** alias of the `ForEach-Object` cmdlet and omits the names of the **MemberName** and **ArgumentList** parameters, which are optional.
Microsoft.PowerShell.Core New Pssession (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/New-PSSession.md
--- external help file: System.Management.Automation.dll-Help.xml
-keywords: powershell,cmdlet
Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 12/20/2019 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/new-pssession?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: New-PSSession --- # New-PSSession
-## SYNOPSIS
+## Synopsis
Creates a persistent connection to a local or remote computer.
-## SYNTAX
+## Syntax
### ComputerName (Default)
New-PSSession [-Name <String[]>] [-ConfigurationName <String>] -ContainerId <Str
### UseWindowsPowerShellParameterSet ```
-New-PSSession [-Name <String[]>] [-UseWindowsPowerShell] [<CommonParameters>]
+New-PSSession -UseWindowsPowerShell [-Name <string[]>] [<CommonParameters>]
``` ### SSHHost
New-PSSession [-Name <String[]>] [-Port <Int32>] [-HostName] <String[]> [-UserNa
New-PSSession [-Name <String[]>] -SSHConnection <Hashtable[]> [<CommonParameters>] ```
-## DESCRIPTION
+## Description
The `New-PSSession` cmdlet creates a PowerShell session (**PSSession**) on a local or remote computer. When you create a **PSSession**, PowerShell establishes a persistent connection to the
connection information. For more information about how to set up PowerShell SSH
> this if you are in an environment where you can be certain of the server certificate and the > network connection to the target system.
-## EXAMPLES
+## Examples
### Example 1: Create a session on the local computer
This example shows how to create multiple sessions using Secure Shell (SSH) and
contain connection information for each session. Note that this example requires that the target remote computers have SSH configured to support key based user authentication.
-## PARAMETERS
+## Parameters
### -AllowRedirection
Accept wildcard characters: False
### -UseWindowsPowerShell
-{{ Fill UseWindowsPowerShell Description }}
+Creates a remote connection to a new Windows PowerShell runspace on the local system.
```yaml Type: System.Management.Automation.SwitchParameter
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable
-WarningAction, and -WarningVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).
-## INPUTS
+## Inputs
### System.String, System.URI, System.Management.Automation.Runspaces.PSSession You can pipe a string, URI, or session object to this cmdlet.
-## OUTPUTS
+## Outputs
### System.Management.Automation.Runspaces.PSSession
-## NOTES
+## Notes
- This cmdlet uses the PowerShell remoting infrastructure. To use this cmdlet, the local computer and any remote computers must be configured for PowerShell remoting. For more
You can pipe a string, URI, or session object to this cmdlet.
more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core).
-## RELATED LINKS
+## Related Links
[Connect-PSSession](Connect-PSSession.md)
You can pipe a string, URI, or session object to this cmdlet.
[Receive-PSSession](Receive-PSSession.md) [Remove-PSSession](Remove-PSSession.md)-
Microsoft.PowerShell.Core About Functions Advanced Parameters (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Parameters.md
---
-description: Explains how to add parameters to advanced functions.
+description: Explains how to add parameters to advanced functions.
+keywords: powershell,cmdlet
Locale: en-US Previously updated : 07/12/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Functions Advanced Parameters
that has the following characteristics:
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
+## Switch parameters
+
+Switch parameters are parameters that take no parameter value.
+Instead, they convey a Boolean true-or-false value through their presence or absence,
+so that when a switch parameter is present it has a **true** value
+and when absent it has a **false** value.
+
+For example, the **Recurse** parameter of `Get-ChildItem` is a switch
+parameter.
+
+To create a switch parameter in a function, specify the `switch` type in the
+parameter definition.
+
+For example, your function may have an option to output data as a byte array:
+
+```powershell
+Param([switch]$AsByteArray)
+```
+
+Switch parameters are easy to use and are preferred over Boolean parameters,
+which have a less natural syntax for PowerShell.
+
+For example, to use a switch parameter, the user types the parameter in the
+command.
+
+`-IncludeAll`
+
+To use a Boolean parameter, the user types the parameter and a Boolean value.
+
+`-IncludeAll $true`
+
+When creating switch parameters, choose the parameter name carefully. Be sure
+that the parameter name communicates the effect of the parameter to the user.
+Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
+value is required.
+
+### Switch parameter design considerations
+
+- Switch parameters should not be given default values. They should always
+ default to false.
+- Switch parameters should be designed so that setting them moves a command
+ from its default functionality to a less common or more complicated mode. The
+ simplest behavior of a command should be the default behavior that does not
+ require the use of switch parameters.
+- Switch parameters should not be mandatory, since that defeats the purpose of
+ a switch; a mandatory switch can only take one value. The only case where is
+ is necessary to make a switch parameter mandatory is when it is needed to
+ differentiate a parameter set. In this case, the switch parameter must be
+ mandatory.
+- Explicitly setting a switch from a boolean can be done with
+ `-MySwitch:$boolValue` and in splatting with
+ `$params = @{ MySwitch = $boolValue }`.
+- Switch parameters are of type `SwitchParameter` but implicitly convert to
+ Boolean. The parameter variable can be used directly in a conditional
+ expression. For example:
+
+ `if ($MySwitch) { ... }`
+
+ There's no need to write `if ($MySwitch.IsPresent) { ... }`
+
+## Dynamic parameters
+
+Dynamic parameters are parameters of a cmdlet, function, or script that are
+available only under certain conditions.
+
+For example, several provider cmdlets have parameters that are available only
+when the cmdlet is used in the provider drive, or in a particular path of the
+provider drive. For example, the **Encoding** parameter is available on the
+`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
+a file system drive.
+
+You can also create a parameter that appears only when another parameter is
+used in the function command or when another parameter has a certain value.
+
+Dynamic parameters can be useful, but use them only when necessary, because
+they can be difficult for users to discover. To find a dynamic parameter, the
+user must be in the provider path, use the **ArgumentList** parameter of the
+`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
+
+To create a dynamic parameter for a function or script, use the `DynamicParam`
+keyword.
+
+The syntax is as follows:
+
+`dynamicparam {<statement-list>}`
+
+In the statement list, use an `if` statement to specify the conditions under
+which the parameter is available in the function.
+
+The following example shows a function with standard parameters named **Name**
+and **Path**, and an optional dynamic parameter named **KeyCount**. The
+**KeyCount** parameter is in the `ByRegistryPath` parameter set and has a type
+of `Int32`. The **KeyCount** parameter is available in the `Get-Sample`
+function only when the value of the **Path** parameter starts with `HKLM:`,
+indicating that it's being used in the `HKEY_LOCAL_MACHINE` registry drive.
+
+```powershell
+function Get-Sample {
+ [CmdletBinding()]
+ Param([string]$Name, [string]$Path)
+
+ DynamicParam
+ {
+ if ($Path.StartsWith("HKLM:"))
+ {
+ $parameterAttribute = [System.Management.Automation.ParameterAttribute]@{
+ ParameterSetName = "ByRegistryPath"
+ Mandatory = $false
+ }
+
+ $attributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
+ $attributeCollection.Add($parameterAttribute)
+
+ $dynParam1 = [System.Management.Automation.RuntimeDefinedParameter]::new(
+ 'KeyCount', [Int32], $attributeCollection
+ )
+
+ $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
+ $paramDictionary.Add('KeyCount', $dynParam1)
+ return $paramDictionary
+ }
+ }
+}
+```
+
+For more information, see the documentation for the
+[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter)
+type.
+ ## Attributes of parameters This section describes the attributes that you can add to function parameters.
The following example declares the **ComputerName** parameter. It uses the
```powershell Param( [Parameter(Mandatory=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
value in the command.
```powershell Param( [Parameter(Position=0)]
- [String[]]
+ [string[]]
$ComputerName ) ```
parameter set, a **UserName** parameter in the `User` parameter set, and a
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false)]
- [Switch]
+ [switch]
$Summary ) ```
the `Computer` parameter set and mandatory in the `User` parameter set.
Param( [Parameter(Mandatory=$true, ParameterSetName="Computer")]
- [String[]]
+ [string[]]
$ComputerName, [Parameter(Mandatory=$true, ParameterSetName="User")]
- [String[]]
+ [string[]]
$UserName, [Parameter(Mandatory=$false, ParameterSetName="Computer")] [Parameter(Mandatory=$true, ParameterSetName="User")]
- [Switch]
+ [switch]
$Summary ) ```
and accepts an object that's passed to the function from the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
the function through the pipeline.
Param( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
- [String[]]
+ [string[]]
$ComputerName ) ```
for the function (for example, `.SYNOPSIS`) then this message also shows up in
Param( [Parameter(Mandatory=$true, HelpMessage="Enter one or more computer names separated by commas.")]
- [String[]]
+ [string[]]
$ComputerName ) ```
The following example shows a parameter declaration that adds the **CN** and
Param( [Parameter(Mandatory=$true)] [Alias("CN","MachineName")]
- [String[]]
+ [string[]]
$ComputerName ) ```
for a mandatory **Path** parameter that supports wildcard values.
Param( [Parameter(Mandatory=$true)] [SupportsWildcards()]
- [String[]]
+ [string[]]
$Path ) ```
developer must implement the code to handle the wildcard input. The wildcards
supported can vary according to the underlying API or PowerShell provider. For more information, see [about_Wildcards](about_Wildcards.md).
-### Parameter and variable validation attributes
+## Argument completion attributes
+
+### ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated.
+
+This attribute was introduced in PowerShell Core 6.0
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompletions-attribute).
+
+### ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion. Similar to **DynamicParameters**, the
+available values are calculated at runtime when the user presses <kbd>Tab</kbd>
+after the parameter name.
+
+For more information, see
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md#argumentcompleter-attribute).
+
+## Parameter and variable validation attributes
Validation attributes direct PowerShell to test the parameter values that users submit when they call the advanced function. If the parameter values fail the
test, an error is generated and the function isn't called. Parameter validation
is only applied to the input provided and any other values like default values are not validated.
-You can also use the validation attributes to restrict the values that
-users can specify for variables. When you use a type converter along with a
-validation attribute, the type converter has to be defined before the attribute.
+You can also use the validation attributes to restrict the values that users
+can specify for variables. When you use a type converter along with a
+validation attribute, the type converter has to be defined before the
+attribute.
```powershell [int32][AllowNull()] $number = 7 ```
+> [!NOTE]
+> Validation attributes can be applied to any variable, not just parameters.
+> You can define validation for any variable within a script.
+ ### AllowNull validation attribute The **AllowNull** attribute allows the value of a mandatory parameter to be
parameter that can have an empty string value.
Param( [Parameter(Mandatory=$true)] [AllowEmptyString()]
- [String]
+ [string]
$ComputerName ) ```
parameter to be an empty collection `@()`. The following example declares a
Param( [Parameter(Mandatory=$true)] [AllowEmptyCollection()]
- [String[]]
+ [string[]]
$ComputerName ) ```
takes one to five parameter values.
Param( [Parameter(Mandatory=$true)] [ValidateCount(1,5)]
- [String[]]
+ [string[]]
$ComputerName ) ```
In the following example, each computer name must have one to ten characters.
Param( [Parameter(Mandatory=$true)] [ValidateLength(1,10)]
- [String[]]
+ [string[]]
$ComputerName ) ```
and each digit must be a number zero to nine.
Param( [Parameter(Mandatory=$true)] [ValidatePattern("[0-9][0-9][0-9][0-9]")]
- [String[]]
+ [string[]]
$ComputerName ) ```
High.
Param( [Parameter(Mandatory=$true)] [ValidateSet("Low", "Average", "High")]
- [String[]]
+ [string[]]
$Detail ) ```
Chocolate, Strawberry, or Vanilla.
```powershell [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
-[String]$flavor = "Strawberry"
+[string]$flavor = "Strawberry"
``` The validation occurs whenever that variable is assigned even within the
script. For example, the following results in an error at runtime:
```powershell Param( [ValidateSet("hello", "world")]
- [String]$Message
+ [string]$Message
) $Message = "bye" ```
-#### Dynamic validateSet values
+This example returns the following error at runtime:
+
+```Output
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+Using `ValidateSet` also enable tab expansion of values for that parameter. For
+more information, see [about_Tab_Expansion](about_Tab_Expansion.md).
+
+#### Dynamic ValidateSet values using classes
You can use a **Class** to dynamically generate the values for **ValidateSet** at runtime. In the following example, the valid values for the variable
filesystem paths for available sound files:
```powershell Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
- [String[]] GetValidValues() {
+ [string[]] GetValidValues() {
$SoundPaths = '/System/Library/Sounds/', '/Library/Sounds','~/Library/Sounds' $SoundNames = ForEach ($SoundPath in $SoundPaths) {
Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
(Get-ChildItem $SoundPath).BaseName } }
- return [String[]] $SoundNames
+ return [string[]] $SoundNames
} } ```
as follows:
```powershell Param( [ValidateSet([SoundNames])]
- [String]$Sound
+ [string]$Sound
) ```
empty string (`""`), or an empty array `@()`.
Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
- [String[]]
+ [string[]]
$UserName ) ```
If you use relative path, the current drive must be in the allowed drive list.
```powershell Param( [ValidateDrive("C", "D", "Variable", "Function")]
- [String]$Path
+ [string]$Path
) ```
If you use relative path, the current drive must be `User`.
function Test-UserDrivePath{ [OutputType([bool])] Param(
- [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][String]$Path
+ [Parameter(Mandatory=, Position=0)][ValidateUserDrive()][string]$Path
) $True }
This attribute was added in PowerShell 6.1.1.
At this time, the attribute is used internally by PowerShell itself and is not intended for external usage.
-## Dynamic parameters
-
-Dynamic parameters are parameters of a cmdlet, function, or script that are
-available only under certain conditions.
-
-For example, several provider cmdlets have parameters that are available only
-when the cmdlet is used in the provider drive, or in a particular path of the
-provider drive. For example, the **Encoding** parameter is available on the
-`Add-Content`, `Get-Content`, and `Set-Content` cmdlets only when it's used in
-a file system drive.
-
-You can also create a parameter that appears only when another parameter is
-used in the function command or when another parameter has a certain value.
-
-Dynamic parameters can be useful, but use them only when necessary, because
-they can be difficult for users to discover. To find a dynamic parameter, the
-user must be in the provider path, use the **ArgumentList** parameter of the
-`Get-Command` cmdlet, or use the **Path** parameter of `Get-Help`.
-
-To create a dynamic parameter for a function or script, use the `DynamicParam`
-keyword.
-
-The syntax is as follows:
-
-`DynamicParam {<statement-list>}`
-
-In the statement list, use an `If` statement to specify the conditions under
-which the parameter is available in the function.
-
-Use the `New-Object` cmdlet to create a
-**System.Management.Automation.RuntimeDefinedParameter** object to represent
-the parameter and specify its name.
-
-You can use a `New-Object` command to create a
-**System.Management.Automation.ParameterAttribute** object to represent
-attributes of the parameter, such as **Mandatory**, **Position**, or
-**ValueFromPipeline** or its parameter set.
-
-The following example shows a sample function with standard parameters named
-**Name** and **Path**, and an optional dynamic parameter named **DP1**. The
-**DP1** parameter is in the `PSet1` parameter set and has a type of `Int32`.
-The **DP1** parameter is available in the `Get-Sample` function only when the
-value of the **Path** parameter starts with `HKLM:`, indicating that it's being
-used in the `HKEY_LOCAL_MACHINE` registry drive.
-
-```powershell
-function Get-Sample {
- [CmdletBinding()]
- Param([String]$Name, [String]$Path)
-
- DynamicParam
- {
- if ($Path.StartsWith("HKLM:"))
- {
- $attributes = New-Object -Type `
- System.Management.Automation.ParameterAttribute
- $attributes.ParameterSetName = "PSet1"
- $attributes.Mandatory = $false
- $attributeCollection = New-Object `
- -Type System.Collections.ObjectModel.Collection[System.Attribute]
- $attributeCollection.Add($attributes)
-
- $dynParam1 = New-Object -Type `
- System.Management.Automation.RuntimeDefinedParameter("DP1", [Int32],
- $attributeCollection)
-
- $paramDictionary = New-Object `
- -Type System.Management.Automation.RuntimeDefinedParameterDictionary
- $paramDictionary.Add("DP1", $dynParam1)
- return $paramDictionary
- }
- }
-}
-```
-
-For more information, see
-[RuntimeDefinedParameter](/dotnet/api/system.management.automation.runtimedefinedparameter).
-
-## Switch parameters
-
-Switch parameters are parameters with no parameter value. They're effective
-only when they're used and have only one effect.
-
-For example, the **NoProfile** parameter of **powershell.exe** is a switch
-parameter.
-
-To create a switch parameter in a function, specify the `Switch` type in the
-parameter definition.
-
-For example:
-
-```powershell
-Param([Switch]<ParameterName>)
-```
-
-Or, you can use an another method:
-
-```powershell
-Param(
- [Parameter(Mandatory=$false)]
- [Switch]
- $<ParameterName>
-)
-```
-
-Switch parameters are easy to use and are preferred over Boolean parameters,
-which have a more difficult syntax.
-
-For example, to use a switch parameter, the user types the parameter in the
-command.
-
-`-IncludeAll`
-
-To use a Boolean parameter, the user types the parameter and a Boolean value.
-
-`-IncludeAll:$true`
-
-When creating switch parameters, choose the parameter name carefully. Be sure
-that the parameter name communicates the effect of the parameter to the user.
-Avoid ambiguous terms, such as **Filter** or **Maximum** that might imply a
-value is required.
-
-## ArgumentCompleter attribute
-
-The **ArgumentCompleter** attribute allows you to add tab completion values to
-a specific parameter. An **ArgumentCompleter** attribute must be defined for
-each parameter that needs tab completion. Similar to **DynamicParameters**, the
-available values are calculated at runtime when the user presses <kbd>Tab</kbd>
-after the parameter name.
-
-To add an **ArgumentCompleter** attribute, you need to define a script block
-that determines the values. The script block must take the following
-parameters in the order specified below. The parameter's names don't matter as
-the values are provided positionally.
-
-The syntax is as follows:
-
-```powershell
-Param(
- [Parameter(Mandatory)]
- [ArgumentCompleter({
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
- # Perform calculation of tab completed values here.
- })]
-)
-```
-
-### ArgumentCompleter script block
-
-The script block parameters are set to the following values:
--- `$commandName` (Position 0) - This parameter is set to the name of the
- command for which the script block is providing tab completion.
-- `$parameterName` (Position 1) - This parameter is set to the parameter whose
- value requires tab completion.
-- `$wordToComplete` (Position 2) - This parameter is set to value the user has
- provided before they pressed <kbd>Tab</kbd>. Your script block should use
- this value to determine tab completion values.
-- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
- Tree (AST) for the current input line. For more information, see
- [Ast Class](/dotnet/api/system.management.automation.language.ast).
-- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
- containing the `$PSBoundParameters` for the cmdlet, before the user pressed
- <kbd>Tab</kbd>. For more information, see
- [about_Automatic_Variables](about_Automatic_Variables.md).
-
-The **ArgumentCompleter** script block must unroll the values using the
-pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
-Returning an array of values causes PowerShell to treat the entire array as
-**one** tab completion value.
-
-The following example adds tab completion to the **Value** parameter. If only
-the **Value** parameter is specified, all possible values, or arguments, for
-**Value** are displayed. When the **Type** parameter is specified, the
-**Value** parameter only displays the possible values for that type.
-
-In addition, the `-like` operator ensures that if the user types the following
-command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
-
-`Test-ArgumentCompleter -Type Fruits -Value A`
-
-```powershell
-function Test-ArgumentCompleter {
-[CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ValidateSet('Fruits', 'Vegetables')]
- $Type,
- [Parameter(Mandatory=$true)]
- [ArgumentCompleter( {
- param ( $commandName,
- $parameterName,
- $wordToComplete,
- $commandAst,
- $fakeBoundParameters )
-
- $possibleValues = @{
- Fruits = @('Apple', 'Orange', 'Banana')
- Vegetables = @('Tomato', 'Squash', 'Corn')
- }
- if ($fakeBoundParameters.ContainsKey('Type'))
- {
- $possibleValues[$fakeBoundParameters.Type] | Where-Object {
- $_ -like "$wordToComplete*"
- }
- }
- else
- {
- $possibleValues.Values | ForEach-Object {$_}
- }
- } )]
- $Value
- )
-}
-```
-
-## ArgumentCompletions attribute
-
-The **ArgumentCompletions** attribute allows you to add tab completion values
-to a specific parameter. An **ArgumentCompletions** attribute must be defined
-for each parameter that needs tab completion. The **ArgumentCompletions**
-attribute is similar to **ValidateSet**. Both attributes take a list of values
-to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
-However, unlike **ValidateSet**, the values are not validated. Therefore the
-user can supply any value, not just the values in the list.
-
-The **ArgumentCompletions** attribute should not be confused with the
-**ArgumentCompleter** attribute, which needs a scriptblock to define the
-options. the specified values are available
-
-The syntax is as follows:
-
-```powershell
-function Test-ArgumentCompletions {
- [CmdletBinding()]
- param (
- [Parameter(Mandatory=$true)]
- [ArgumentCompletions('Fruits', 'Vegetables')]
- $Type,
-
- [Parameter()]
- [ArgumentCompletions('Apple', 'Banana', 'Orange')]
- $Fruit,
-
- [Parameter()]
- [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
- $Vegetable
- )
-}
-```
-
-Each of the parameters is provided a list of options to the
-**ArgumentCompletions** attribute to enable tab completion.
-
-This attribute was introduced in PowerShell Core 6.0
- ## See also [about_Automatic_Variables](about_Automatic_Variables.md)
Microsoft.PowerShell.Core About Functions Argument Completion (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Functions_Argument_Completion.md
+---
Last updated : 07/27/2021
+description: Explains the various argument completion options available for function parameters.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_argument_completion?view=powershell-7.2&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About functions argument completion
+---
+# about_Functions_Argument_Completion
+
+## Short description
+Argument completion is a feature of PowerShell that provide hints, enables
+discovery, and speeds up input entry of argument values.
+
+## Long description
+
+This article describe the different ways you can implement argument completers
+for PowerShell functions. Argument completers provide the possible values for a
+parameter. The available values are calculated at runtime when the user presses
+the <kbd>Tab</kbd> key after the parameter name. There are several ways to
+define an argument completer for a parameter.
+
+> [!NOTE]
+> <kbd>Tab</kbd> is the default key binding on Windows. This keybinding can be
+> changed by the PSReadLine module or the application that is hosting
+> PowerShell. The keybinding is different on non-Windows platforms. For more
+> information, see
+> [about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+## ValidateSet attribute
+
+The **ValidateSet** attribute specifies a set of valid values for a parameter
+or variable and enables tab completion. PowerShell generates an error if a
+parameter or variable value doesn't match a value in the set. In the following
+example, the value of the **Fruit** parameter can only be **Apple**,
+**Banana**, or **Pear**.
+
+```powershell
+Param(
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Apple', 'Banana', 'Pear')]
+ [string[]]
+ $Fruit
+)
+```
+
+In the following example, the value of the variable `$flavor` must be either
+**Chocolate**, **Strawberry**, or **Vanilla**. The `ValidateSet` attribute can
+be used on any variable, not just parameters.
+
+```powershell
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')]
+[string]$flavor = 'Strawberry'
+```
+
+The validation occurs whenever that variable is assigned even within the
+script.
+
+```powershell
+Param(
+ [ValidateSet('hello', 'world')]
+ [string]$Message
+)
+
+$Message = 'bye'
+```
+
+This example returns the following error at runtime:
+
+```
+MetadataError: The attribute cannot be added because variable Message with
+value bye would no longer be valid.
+```
+
+For more information about tab expansion, see
+[about_Tab_Expansion](about_Tab_Expansion.md).
+
+### Dynamic ValidateSet values using classes
+
+You can use a **Class** to dynamically generate the values for **ValidateSet**
+at runtime. In the following example, the valid values for the variable
+`$Sound` are generated via a **Class** named **SoundNames** that checks three
+filesystem paths for available sound files:
+
+```powershell
+Class SoundNames : System.Management.Automation.IValidateSetValuesGenerator {
+ [string[]] GetValidValues() {
+ $SoundPaths = '/System/Library/Sounds/',
+ '/Library/Sounds',
+ '~/Library/Sounds'
+ $SoundNames = ForEach ($SoundPath in $SoundPaths) {
+ If (Test-Path $SoundPath) {
+ (Get-ChildItem $SoundPath).BaseName
+ }
+ }
+ return [string[]] $SoundNames
+ }
+}
+```
+
+The `[SoundNames]` class is then implemented as a dynamic **ValidateSet** value
+as follows:
+
+```powershell
+Param(
+ [ValidateSet([SoundNames])]
+ [string]$Sound
+)
+```
+
+> [!NOTE]
+> The `IValidateSetValuesGenerator` class was introduced in PowerShell 6.0.
+
+## ArgumentCompletions attribute
+
+The **ArgumentCompletions** attribute allows you to add tab completion values
+to a specific parameter. An **ArgumentCompletions** attribute must be defined
+for each parameter that needs tab completion. The **ArgumentCompletions**
+attribute is similar to **ValidateSet**. Both attributes take a list of values
+to be presented when the user presses <kbd>Tab</kbd> after the parameter name.
+However, unlike **ValidateSet**, the values are not validated and more like
+suggestions. Therefore the user can supply any value, not just the values in
+the list.
+
+The **ArgumentCompletions** attribute should not be confused with the
+**ArgumentCompleter** attribute, which needs a scriptblock to define the
+options. the specified values are available
+
+The syntax is as follows:
+
+```powershell
+function Test-ArgumentCompletions {
+ [CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompletions('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter()]
+ [ArgumentCompletions('Apple', 'Banana', 'Orange')]
+ $Fruit,
+
+ [Parameter()]
+ [ArgumentCompletions('Tomato', 'Corn', 'Squash')]
+ $Vegetable
+ )
+}
+```
+
+Each of the parameters is provided a list of options to the
+**ArgumentCompletions** attribute to enable tab completion.
+
+This attribute was introduced in PowerShell Core 6.0
+
+## ArgumentCompleter attribute
+
+The **ArgumentCompleter** attribute allows you to add tab completion values to
+a specific parameter. An **ArgumentCompleter** attribute must be defined for
+each parameter that needs tab completion.
+
+To add an **ArgumentCompleter** attribute, you need to define a script block
+that determines the values. The script block must take the following
+parameters in the order specified below. The parameter's names don't matter as
+the values are provided positionally.
+
+The syntax is as follows:
+
+```powershell
+function MyArgumentCompleter {
+ Param(
+ [Parameter(Mandatory)]
+ [ArgumentCompleter( {
+ param ( $commandName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+ # Perform calculation of tab completed values here.
+ } )]
+ $ParamName
+ )
+}
+```
+
+### ArgumentCompleter script block
+
+The script block parameters are set to the following values:
+
+- `$commandName` (Position 0) - This parameter is set to the name of the
+ command for which the script block is providing tab completion.
+- `$parameterName` (Position 1) - This parameter is set to the parameter whose
+ value requires tab completion.
+- `$wordToComplete` (Position 2) - This parameter is set to value the user has
+ provided before they pressed <kbd>Tab</kbd>. Your script block should use
+ this value to determine tab completion values.
+- `$commandAst` (Position 3) - This parameter is set to the Abstract Syntax
+ Tree (AST) for the current input line. For more information, see the
+ [AST](/dotnet/api/system.management.automation.language.ast) type
+ documentation.
+- `$fakeBoundParameters` (Position 4) - This parameter is set to a hashtable
+ containing the `$PSBoundParameters` for the cmdlet, before the user pressed
+ <kbd>Tab</kbd>. For more information, see
+ [about_Automatic_Variables](about_Automatic_Variables.md).
+
+The **ArgumentCompleter** script block must unroll the values using the
+pipeline, such as `ForEach-Object`, `Where-Object`, or another suitable method.
+Returning an array of values causes PowerShell to treat the entire array as
+**one** tab completion value.
+
+The following example adds tab completion to the **Value** parameter. If only
+the **Value** parameter is specified, all possible values, or arguments, for
+**Value** are displayed. When the **Type** parameter is specified, the
+**Value** parameter only displays the possible values for that type.
+
+In addition, the `-like` operator ensures that if the user types the following
+command and uses <kbd>Tab</kbd> completion, only **Apple** is returned.
+
+`Test-ArgumentCompleter -Type Fruits -Value A`
+
+```powershell
+function MyArgumentCompleter{
+ param ( $commaName,
+ $parameterName,
+ $wordToComplete,
+ $commandAst,
+ $fakeBoundParameters )
+
+ $possibleValues = @{
+ Fruits = @('Apple', 'Orange', 'Banana')
+ Vegetables = @('Tomato', 'Squash', 'Corn')
+ }
+
+ if ($fakeBoundParameters.ContainsKey('Type')) {
+ $possibleValues[$fakeBoundParameters.Type] | Where-Object {
+ $_ -like "$wordToComplete*"
+ }
+ } else {
+ $possibleValues.Values | ForEach-Object {$_}
+ }
+}
+
+function Test-ArgumentCompleter {
+[CmdletBinding()]
+ param (
+ [Parameter(Mandatory=$true)]
+ [ValidateSet('Fruits', 'Vegetables')]
+ $Type,
+
+ [Parameter(Mandatory=$true)]
+ [ArgumentCompleter({ MyArgumentCompleter @args })]
+ $Value
+ )
+}
+```
+
+## Class-based argument completers
+
+Beginning in PowerShell 7.2, a new feature was added that allows you to define
+more generic implementations of parameterized argument completers.
+
+By deriving from `ArgumentCompleterAttribute`, it's possible to create generic
+completers that can be reused, for example:
+
+```powershell
+[DirectoryCompleter(ContainingFile="pswh.exe", Depth=2)]
+
+[DateCompleter(WeekDay='Monday', From="LastYear")]
+
+[GitCommits(Branch='release')]
+```
+
+The derived attributes must implement the `IArgumentCompleterFactory` interface
+and use property values to create a specialized completer.
+
+```powershell
+using namespace System.Collections
+using namespace System.Collections.Generic
+using namespace System.Management.Automation
+using namespace System.Management.Automation.Language
+
+class NumberCompleter : IArgumentCompleter {
+
+ [int] $From
+ [int] $To
+ [int] $Step
+
+ NumberCompleter([int] $from, [int] $to, [int] $step) {
+ if ($from -gt $to) {
+ throw [ArgumentOutOfRangeException]::new("from")
+ }
+ $this.From = $from
+ $this.To = $to
+ $this.Step = $step -lt 1 ? 1 : $step
+ }
+
+ [IEnumerable[CompletionResult]] CompleteArgument(
+ [string] $CommandName,
+ [string] $parameterName,
+ [string] $wordToComplete,
+ [CommandAst] $commandAst,
+ [IDictionary] $fakeBoundParameters) {
+
+ $resultList = [List[CompletionResult]]::new()
+ $local:to = $this.To
+ $local:step = $this.Step
+ for ($i = $this.From; $i -lt $to; $i += $step) {
+ $resultList.Add([CompletionResult]::new($i.ToString()))
+ }
+
+ return $resultList
+ }
+}
+
+class NumberCompletionsAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory {
+ [int] $From
+ [int] $To
+ [int] $Step
+
+ NumberCompletionsAttribute([int] $from, [int] $to, [int] $step) {
+ $this.From = $from
+ $this.To = $to
+ $this.Step = $step
+ }
+
+ [IArgumentCompleter] Create() { return [NumberCompleter]::new($this.From, $this.To, $this.Step) }
+}
+```
+
+Usage from PowerShell would then be:
+
+```powershell
+function Add{
+ param(
+ [NumberCompletions(0, 100, 5)]
+ [int] $X,
+
+ [NumberCompletions(0, 100, 5)]
+ [int] $Y
+ )
+ $X + $Y
+}
+```
+
+## Register-ArgumentCompleter
+
+The `Register-ArgumentCompleter` cmdlet registers a custom argument completer.
+An argument completer allows you to provide dynamic tab completion, at run time
+for any command that you specify.
+
+For more information, see
+[Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter).
+
+## See also
+
+- [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md)
+- [Register-ArgumentCompleter](xref:Microsoft.PowerShell.Core.Register-ArgumentCompleter)
+- [about_Tab_Expansion](about_Tab_Expansion.md)
Microsoft.PowerShell.Core About Remote Requirements (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md
--- description: Describes the system requirements and configuration requirements for running remote commands in PowerShell. Locale: en-US Previously updated : 01/03/2018 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_requirements?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Requirements --- # about_Remote_Requirements
-## SHORT DESCRIPTION
+## Short description
Describes the system requirements and configuration requirements for running remote commands in PowerShell.
-## LONG DESCRIPTION
+## Long description
This topic describes the system requirements, user requirements, and resource requirements for establishing remote connections and running remote commands in PowerShell. It also provides instructions for configuring remote operations.
-Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject,
-Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by
-using Microsoft .NET Framework methods to retrieve the objects. They do not
-use the PowerShell remoting infrastructure. The requirements in this
-document do not apply to these cmdlets.
+> [!NOTE]
+> Many cmdlets (including the `Get-Service`, `Get-Process`, `Get-WMIObject`,
+> `Get-EventLog`, and `Get-WinEvent` cmdlets) get objects from remote computers
+> by using Microsoft .NET Framework methods to retrieve the objects. They do
+> not use the PowerShell remoting infrastructure. The requirements in this
+> document do not apply to these cmdlets.
-To find the cmdlets that have a ComputerName parameter but do not use
-PowerShell remoting, read the description of the ComputerName parameter of the
-cmdlets.
+To find the cmdlets that have a **ComputerName** parameter but do not use
+PowerShell remoting, read the description of the **ComputerName**
+parameter of the cmdlets.
-## SYSTEM REQUIREMENTS
+## System requirements
To run remote sessions on Windows PowerShell 3.0, the local and remote computers must have the following:
PowerShell 3.0, such as the ability to disconnect and reconnect to sessions,
are available only when both computers are running Windows PowerShell 3.0. To find the version number of an installed version of PowerShell,
-use the $PSVersionTable automatic variable.
+use the `$PSVersionTable` automatic variable.
Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are included in Windows 8, Windows Server 2012, and newer releases of the Windows
operating system. WinRM 3.0 is included in Windows Management Framework 3.0
for older operating systems. If the computer does not have the required version of WinRM or the Microsoft .NET Framework, the installation fails.
-## USER PERMISSIONS
+## User permissions
To create remote sessions and run remote commands, by default, the current
-user must be a member of the Administrators group on the remote computer or
+user must be a member of the **Administrators** group on the remote computer or
provide the credentials of an administrator. Otherwise, the command fails. The permissions required to create sessions and run commands on a remote computer (or in a remote session on the local computer) are established by the
-session configuration (also known as an "endpoint") on the remote computer to
+session configuration (also known as an **endpoint**) on the remote computer to
which the session connects. Specifically, the security descriptor on the session configuration determines who has access to the session configuration and who can use it to connect. The security descriptors on the default session configurations,
-Microsoft.PowerShell, Microsoft.PowerShell32, and
-Microsoft.PowerShell.Workflow, allow access only to members of the
-Administrators group.
+**Microsoft.PowerShell**, **Microsoft.PowerShell32**, and
+**Microsoft.PowerShell.Workflow**, allow access only to members of the
+**Administrators** group.
If the current user doesn't have permission to use the session configuration, the command to run a command (which uses a temporary session) or create a
persistent session on the remote computer fails. The user can use the
ConfigurationName parameter of cmdlets that create sessions to select a different session configuration, if one is available.
-Members of the Administrators group on a computer can determine who has
+Members of the **Administrators** group on a computer can determine who has
permission to connect to the computer remotely by changing the security descriptors on the default session configurations and by creating new session configurations with different security descriptors.
configurations with different security descriptors.
For more information about session configurations, see [about_Session_Configurations](about_Session_Configurations.md).
-## WINDOWS NETWORK LOCATIONS
+## Windows network locations
-Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable
+Beginning in Windows PowerShell 3.0, the `Enable-PSRemoting` cmdlet can enable
remoting on client and server versions of Windows on private, domain, and public networks.
Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted remote
access. It also creates a firewall rule for public networks that allows remote access only from computers in the same local subnet. This local subnet firewall rule is enabled by default on server versions of Windows on public
-networks, but Enable-PSRemoting reapplies the rule in case it was changed or
+networks, but `Enable-PSRemoting` reapplies the rule in case it was changed or
deleted. On client versions of Windows with private and domain networks, by default,
-the Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted
+the `Enable-PSRemoting` cmdlet creates firewall rules that allow unrestricted
remote access. To enable remoting on client versions of Windows with public networks, use the
-SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates
+**SkipNetworkProfileCheck** parameter of the `Enable-PSRemoting` cmdlet. It creates
a firewall rule that allows remote access only from computers in the same local subnet. To remove the local subnet restriction on public networks and allow remote access from all locations on client and server versions of Windows, use the
-Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following
+`Set-NetFirewallRule` cmdlet in the **NetSecurity** module. Run the following
command: ```powershell Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any ```
-In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling the
+> firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+
+In Windows PowerShell 2.0, on server versions of Windows, `Enable-PSRemoting`
creates firewall rules that permit remote access on all networks.
-In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting
+In Windows PowerShell 2.0, on client versions of Windows, `Enable-PSRemoting`
creates firewall rules only on private and domain networks. If the network
-location is public, Enable-PSRemoting fails.
+location is public, `Enable-PSRemoting` fails.
-## RUN AS ADMINISTRATOR
+## Run as administrator
Administrator privileges are required for the following remoting operations:
Administrator privileges are required for the following remoting operations:
the settings in the LocalHost node of the WSMAN: drive. To perform these tasks, you must start PowerShell with the "Run as
-administrator" option even if you are a member of the Administrators group on
+administrator" option even if you are a member of the **Administrators** group on
the local computer.
-In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with
-the "Run as administrator" option:
+In Windows 7 and in Windows Server 2008 R2, to start PowerShell with
+the **Run as administrator** option:
1. Click Start, click All Programs, click Accessories, and then click
- the Windows PowerShell folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+ the PowerShell folder.
+1. Right-click PowerShell, and then click **Run as administrator**.
-To start Windows PowerShell with the "Run as administrator" option:
+To start Windows PowerShell with the **Run as administrator** option:
-1. Click Start, click All Programs, and then click the Windows PowerShell
+1. Click Start, click All Programs, and then click the PowerShell
folder.
-2. Right-click Windows PowerShell, and then click "Run as administrator".
+1. Right-click PowerShell, and then click **Run as administrator**.
-The "Run as administrator" option is also available in other Windows Explorer
-entries for Windows PowerShell, including shortcuts. Just right-click the
-item, and then click "Run as administrator".
+The **Run as administrator** option is also available in other Windows Explorer
+entries for PowerShell, including shortcuts. Just right-click the
+item, and then click **Run as administrator**.
-When you start Windows PowerShell from another program such as Cmd.exe, use
-the "Run as administrator" option to start the program.
+When you start PowerShell from another program such as Cmd.exe, use
+the **Run as administrator** option to start the program.
-## HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING
+## How to configure your computer for remoting
Computers running all supported versions of Windows can establish remote connections to and run remote commands in PowerShell without any
remoting on the computer.
Windows Server 2012 and newer releases of Windows Server are enabled for PowerShell remoting by default. If the settings are changed, you can
-restore the default settings by running the Enable-PSRemoting cmdlet.
+restore the default settings by running the `Enable-PSRemoting` cmdlet.
On all other supported versions of Windows, you need to run the
-Enable-PSRemoting cmdlet to enable PowerShell remoting.
+`Enable-PSRemoting` cmdlet to enable PowerShell remoting.
The remoting features of PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for
configuration that allow users to connect to WS-Management.
To configure PowerShell to receive remote commands:
-1. Start PowerShell with the "Run as administrator" option.
-2. At the command prompt, type: `Enable-PSRemoting`
+1. Start PowerShell with the **Run as administrator** option.
+1. At the command prompt, type: `Enable-PSRemoting`
To verify that remoting is configured correctly, run a test command such as the following command, which creates a remote session on the local computer.
If remoting is configured correctly, the command will create a session on the
local computer and return an object that represents the session. The output should resemble the following sample output:
-```output
+```Output
Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell
Id Name ComputerName State ConfigurationName
If the command fails, for assistance, see [about_Remote_Troubleshooting](about_Remote_Troubleshooting.md).
-## UNDERSTAND POLICIES
+## Understand policies
When you work remotely, you use two instances of PowerShell, one on the local computer and one on the remote computer. As a result, your work is
In general, before you connect and as you are establishing the connection, the
policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect.
-## Basic Authentication Limitations on Linux and macOS
+## Basic authentication limitations on Linux and macOS
When connecting from a Linux or macOS system to Windows, Basic Authentication over HTTP is not supported. Basic Authentication can be used over HTTPS by
winrm create winrm/config/Listener?Address=*+Transport=HTTPS $hostinfo
On the Linux or macOS side, select Basic for authentication and -UseSSl.
-> NOTE: Basic authentication cannot be used with domain accounts; a local account
-is required and the account must be in the Administrators group.
+> [!NOTE]
+> Basic authentication cannot be used with domain accounts; a local account is
+> required and the account must be in the **Administrators** group.
```powershell # The specified local user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
-Authentication Basic -UseSSL ```
-An alternative to Basic Authentication over HTTPS is Negotiate. This results
-in NTLM authentication between the client and server and payload is encrypted
-over HTTP.
+An alternative to **Basic Authentication** over HTTPS is **Negotiate**. This
+results in NTLM authentication between the client and server and payload is
+encrypted over HTTP.
-The following illustrates using Negotiate with New-PSSession:
+The following illustrates using **Negotiate** with `New-PSSession`:
```powershell # The specified user must have administrator rights on the target machine.
$session = New-PSSession -Computer <hostname> -Credential $cred `
> [!NOTE] > Windows Server requires an additional registry setting to enable > administrators, other than the built in administrator, to connect using NTLM.
-> Refer to the LocalAccountTokenFilterPolicy registry setting under Negotiate
-> Authentication in
-> [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
+> Refer to the **LocalAccountTokenFilterPolicy** registry setting under
+> **Negotiate** Authentication in [Authentication for Remote Connections](/windows/win32/winrm/authentication-for-remote-connections)
-## SEE ALSO
+## See also
[about_Remote](about_Remote.md)
$session = New-PSSession -Computer <hostname> -Credential $cred `
[Enter-PSSession](xref:Microsoft.PowerShell.Core.Enter-PSSession) [New-PSSession](xref:Microsoft.PowerShell.Core.New-PSSession)-
Microsoft.PowerShell.Core About Remote Troubleshooting (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Remote_Troubleshooting.md
--- description: Describes how to troubleshoot remote operations in PowerShell. Locale: en-US Previously updated : 10/27/2020 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_troubleshooting?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Remote Troubleshooting
Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
The `Set-NetFirewallRule` cmdlet is exported by the NetSecurity module.
+> [!NOTE]
+> The name of the firewall rule can be different for different versions of
+> Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling
+> the firewall rule, view the security settings in the rule to verify that the
+> configuration is appropriate for your environment.
+ > [!NOTE] > In Windows PowerShell 2.0, on computers running server versions of Windows, > `Enable-PSRemoting` creates firewall rules that allow remote access on
Microsoft.PowerShell.Core About Tab Expansion (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Tab_Expansion.md
+---
Last updated : 07/27/2021
+description: Explains how to use the Tab Expansion feature in PowerShell.
+Locale: en-US
+online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_tab_expansion?view=powershell-7.2&WT.mc_id=ps-gethelp
+schema: 2.0.0
+ Title: About tab expansion
+---
+# about_Tab_Expansion
+
+## Short description
+PowerShell provides completions on input to provide hints, enable discovery, and
+speed up input entry. Command names, parameter names, argument values and file
+paths can all be completed by pressing the <kbd>Tab</kbd> key.
+
+## Long description
+
+Tab expansion is controlled by the internal function **TabExpansion** or
+**TabExpansion2**. Since this function can be modified or overridden, this
+discussion is a guide to the behavior of the default PowerShell configuration.
+
+The <kbd>Tab</kbd> key is the default key binding on Windows. This keybinding
+can be changed by the PSReadLine module or the application that is hosting
+PowerShell. The keybinding is different on non-Windows platforms. For more
+information, see
+[about_PSReadLine](/powershell/module/psreadline/about/about_psreadline#completion-functions).
+
+> [!NOTE]
+> One limitation of the tab expansion process is that tabs are always
+> interpreted as attempts to complete a word. If you copy and paste command
+> examples into a PowerShell console, make sure that the sample does not
+> contain tabs; if it does, the results will be unpredictable and will almost
+> certainly not be what you intended.
+
+## File and cmdlet name completion
+
+To fill in a filename or path from the available choices automatically, type
+part of the name and press the <kbd>Tab</kbd> key. PowerShell will
+automatically expand the name to the first match that it finds. Pressing the
+<kbd>Tab</kbd> key repeatedly will cycle through all of the available choices.
+
+The tab expansion of cmdlet names is slightly different. To use tab expansion
+on a cmdlet name, type the entire first part of the name (the verb) and the
+hyphen that follows it. You can fill in more of the name for a partial match.
+For example, if you type `get-co` and then press the <kbd>Tab</kbd> key,
+PowerShell will automatically expand this to the `Get-Command` cmdlet (notice
+that it also changes the case of letters to their standard form). If you press
+<kbd>Tab</kbd> key again, PowerShell replaces this with the only other matching
+cmdlet name, `Get-Content`.
+
+> [!NOTE]
+> As of PowerShell 7.0, <kbd>Tab</kbd> will also expand abbreviated cmdlets and
+> functions. For example, `i-psdf<tab>` returns `Import-PowerShellDataFile`.
+
+Tab completion also works to resolve PowerShell alias and native executables.
+
+You can use tab expansion repeatedly on the same line. For example, you can use
+tab expansion on the name of the `Get-Content` cmdlet by entering:
+
+### Examples
+
+```
+PS> Get-Con<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content
+```
+
+You can then partially specify the path to the Active Setup log file and use
+tab expansion again:
+
+```
+PS> Get-Content c:\windows\acts<Tab>
+```
+
+When you press the <kbd>Tab</kbd> key, the command expands to:
+
+```
+PS> Get-Content C:\windows\actsetup.log
+```
+
+PSReadLine also has a menu completion feature. The default key binding on
+Windows is <kbd>Ctrl</kbd>-<kbd>Space</kbd>.
+
+```
+PS> fore<Ctrl-Space>
+```
+
+When you press <kbd>Ctrl</kbd>-<kbd>Space</kbd>, PowerShell presents the full
+list of matching values as a menu:
+
+```
+PS> foreach
+foreach ForEach-Object foreach.cmd
+```
+
+In this example the string 'fore' is matched to `foreach` (PowerShell alias),
+`ForEach-Object` (cmdlet), and `foreach.cmd` (native command). Use the arrow
+keys to select the value you want.
+
+## Parameter argument completion
+
+Tab completion can also work to complete parameter arguments. This allows you
+to use the <kbd>Tab</kbd> key to cycle through a list of possible values that
+are valid for some parameter.
+
+For more information see,
+[about_Functions_Argument_Completion](about_Functions_Argument_Completion.md).
+
+## Enumerated value completion
+
+Beginning in PowerShell 7.0, support for tab completion of enums was added. You
+can use tab completion to select the value you want anywhere an enum is used.
+For example:
+
+```
+enum Suits {
+ Clubs = 0
+ Diamonds = 1
+ Hearts = 2
+ Spades = 3
+}
+
+[Suits]$suit = 'c<Tab>
+```
+
+Enumerated values are strings, so the value to be completed must start with a
+single or double-quote character.
+
+When you hit the <kbd>Tab</kbd> key, you get the following results:
+
+```
+[Suits]$suit = 'Clubs'
+```
+
+Tab completion also works with .NET enumerations.
+
+```
+[System.IO.FileAttributes]$attr = 'S<Tab><Tab>
+```
+
+Hitting the <kbd>Tab</kbd> key twice cycles through the two values that start
+with the letter "S". The end result is:
+
+```
+[System.IO.FileAttributes]$attr = 'System'
+```
+
+Beginning in PowerShell 7.0, tab expansion was added for the values of
+`ValidateSet` when assigning to a variable. For example, if you were typing the
+following variable definition:
+
+```
+[ValidateSet('Chocolate', 'Strawberry', 'Vanilla')][string]$flavor = 'Strawberry'
+$flavor = <tab>
+```
+
+When you hit the <kbd>Tab</kbd> key, you would get the following result:
+
+```
+$flavor = 'Chocolate'
+```
+
+## Tab completions for comment-based keywords
+
+Beginning in PowerShell 7.2, support was added for tab completion of the
+`#requires` parameters and the keywords for comment-based help.
+
+### Example for `#requires` statement
+
+```
+#requires -<Ctrl-Space>
+```
+
+Menu expansion show the following parameter options:
+
+```
+#requires -<Ctrl-Space>
+Modules PSEdition RunAsAdministrator Version
+```
+
+### Example for comment-based help
+
+```
+<#
+ .<Ctrl-Space>
+```
+
+Menu expansion shows the following keyword options:
+
+```
+ <#
+ .COMPONENT
+COMPONENT EXTERNALHELP FUNCTIONALITY NOTES REMOTEHELPRUNSPACE
+DESCRIPTION FORWARDHELPCATEGORY INPUTS OUTPUTS ROLE
+EXAMPLE FORWARDHELPTARGETNAME LINK PARAMETER SYNOPSIS
+```
+
+## See also
+
+- [about_Functions_Argument_Completion](about_Functions_Argument_Completion.md)
+- [about_Requires](about_Requires.md)
+- [about_Comment_Based_Help](about_Comment_Based_Help.md)
Microsoft.PowerShell.Core Foreach Object (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/ForEach-Object.md
external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 03/26/2021 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: ForEach-Object
property value type.
### Example 7: Split module names into component names This example shows three ways to split two dot-separated module names into their component names.
+The commands call the **Split** method of strings. The three commands use different syntax, but they
+are equivalent and interchangeable. The output is the same for all three cases.
```powershell "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")}
PowerShell
Host ```
-The commands call the **Split** method of strings. The three commands use different syntax, but they
-are equivalent and interchangeable.
- The first command uses the traditional syntax, which includes a script block and the current object operator `$_`. It uses the dot syntax to specify the method and parentheses to enclose the delimiter argument. The second command uses the **MemberName** parameter to specify the **Split** method and the
-**ArgumentName** parameter to identify the dot (".") as the split delimiter.
+**ArgumentList** parameter to identify the dot (".") as the split delimiter.
The third command uses the **Foreach** alias of the `ForEach-Object` cmdlet and omits the names of the **MemberName** and **ArgumentList** parameters, which are optional.
state and retrieve data.
This parameter was introduced in PowerShell 7.0. ```yaml
-Type: SwitchParameter
+Type: System.Management.Automation.SwitchParameter
Parameter Sets: ParallelParameterSet Aliases:
Accept wildcard characters: False
Prompts you for confirmation before running the cmdlet. ```yaml
-Type: SwitchParameter
+Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All) Aliases: cf
Accept wildcard characters: False
Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml
-Type: SwitchParameter
+Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All) Aliases: wi
Microsoft.PowerShell.Core New Pssession (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/New-PSSession.md
external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core Previously updated : 12/20/2019 Last updated : 07/27/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/new-pssession?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: New-PSSession
New-PSSession [-Name <String[]>] [-ConfigurationName <String>] -ContainerId <Str
### UseWindowsPowerShellParameterSet ```
-New-PSSession [-Name <String[]>] [-UseWindowsPowerShell] [<CommonParameters>]
+New-PSSession -UseWindowsPowerShell [-Name <string[]>] [<CommonParameters>]
``` ### SSHHost ```
-New-PSSession [-Name <String[]>] [-Port <Int32>] [-HostName] <String[]> [-UserName <String>] [-KeyFilePath <String>]
-[-SSHTransport] [-Subsystem <String>] [-ConnectingTimeout <int>] [<CommonParameters>]
+New-PSSession [-Name <String[]>] [-Port <Int32>] [-HostName] <String[]> [-UserName <String>]
+ [-KeyFilePath <String>] [-SSHTransport] [-Subsystem <String>] [-ConnectingTimeout <int>]
+ [<CommonParameters>]
``` ### SSHHostHashParam
Accept wildcard characters: False
### -UseWindowsPowerShell
-{{ Fill UseWindowsPowerShell Description }}
+Creates a remote connection to a new Windows PowerShell runspace on the local system.
```yaml Type: System.Management.Automation.SwitchParameter
learn Using Tab Expansion https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/docs-conceptual/learn/Using-Tab-Expansion.md
Previously updated : 06/05/2017
-keywords: powershell,cmdlet
Title: Using Tab Expansion
-description: Explains how to use the Tab Expansion feature in PowerShell.
-# Using Tab Expansion
-
-Command-line shells often provide a way to complete the names of long files or commands
-automatically, speeding up command entry and providing hints. PowerShell allows you to fill in file
-names and cmdlet names by pressing the <kbd>Tab</kbd> key.
-
-> [!NOTE]
-> Tab expansion is controlled by the internal function TabExpansion or TabExpansion2. Since this
-> function can be modified or overridden, this discussion is a guide to the behavior of the default
-> PowerShell configuration.
-
-To fill in a filename or path from the available choices automatically, type part of the name and
-press the <kbd>Tab</kbd> key. PowerShell will automatically expand the name to the first match that
-it finds. Pressing the <kbd>Tab</kbd> key repeatedly will cycle through all of the available
-choices.
-
-The tab expansion of cmdlet names is slightly different. To use tab expansion on a cmdlet name, type
-the entire first part of the name (the verb) and the hyphen that follows it. You can fill in more of
-the name for a partial match. For example, if you type `get-co` and then press the <kbd>Tab</kbd>
-key, PowerShell will automatically expand this to the `Get-Command` cmdlet (notice that it also
-changes the case of letters to their standard form). If you press <kbd>Tab</kbd> key again,
-PowerShell replaces this with the only other matching cmdlet name, `Get-Content`.
-
-> [!NOTE]
-> As of PowerShell 7.0, <kbd>Tab</kbd> will also expand abbreviated cmdlets and functions. For
-> example, `i-psdf<tab>` returns `Import-PowerShellDataFile`.
-
-You can use tab expansion repeatedly on the same line. For example, you can use tab expansion on the
-name of the `Get-Content` cmdlet by entering:
-
-```
-PS> Get-Con<Tab>
-```
-
-When you press the <kbd>Tab</kbd> key, the command expands to:
-
-```
-PS> Get-Content
-```
-
-You can then partially specify the path to the Active Setup log file and use tab expansion again:
-
-```
-PS> Get-Content c:\windows\acts<Tab>
-```
-
-When you press the <kbd>Tab</kbd> key, the command expands to:
-
-```
-PS> Get-Content C:\windows\actsetup.log
-```
-
-> [!NOTE]
-> One limitation of the tab expansion process is that tabs are always interpreted as attempts to
-> complete a word. If you copy and paste command examples into a PowerShell console, make sure that
-> the sample does not contain tabs; if it does, the results will be unpredictable and will almost
-> certainly not be what you intended.
learn Running Remote Commands https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/docs-conceptual/learn/remoting/Running-Remote-Commands.md
command on one or more remote computers. You can establish persistent connection
sessions, and run scripts on remote computers. To use Windows PowerShell remoting, the remote computer must be configured for remote management.
-For more information, including instructions, see [About Remote Requirements](/powershell/module/microsoft.powershell.core/about/about_remote_requirements).
+For more information, including instructions, see
+[About Remote Requirements](/powershell/module/microsoft.powershell.core/about/about_remote_requirements).
Once you have configured Windows PowerShell remoting, many remoting strategies are available to you.
-This article lists just a few of them. For more information, see [About Remote](/powershell/module/microsoft.powershell.core/about/about_remote).
+This article lists just a few of them. For more information, see
+[About Remote](/powershell/module/microsoft.powershell.core/about/about_remote).
### Start an Interactive Session
-To start an interactive session with a single remote computer, use the [Enter-PSSession](/powershell/module/microsoft.powershell.core/enter-pssession)
-cmdlet. For example, to start an interactive session with the Server01 remote computer, type:
+To start an interactive session with a single remote computer, use the
+[Enter-PSSession](/powershell/module/microsoft.powershell.core/enter-pssession) cmdlet. For example,
+to start an interactive session with the Server01 remote computer, type:
```powershell Enter-PSSession Server01
For more information about the Enter-PSSession and Exit-PSSession cmdlets, see:
### Run a Remote Command
-To run a command on one or more computers, use the [Invoke-Command](/powershell/module/microsoft.powershell.core/invoke-command)
-cmdlet. For example, to run a [Get-UICulture](/powershell/module/microsoft.powershell.utility/get-uiculture)
-command on the Server01 and Server02 remote computers, type:
+To run a command on one or more computers, use the
+[Invoke-Command](/powershell/module/microsoft.powershell.core/invoke-command) cmdlet. For example,
+to run a [Get-UICulture](/powershell/module/microsoft.powershell.utility/get-uiculture) command on
+the Server01 and Server02 remote computers, type:
```powershell Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {Get-UICulture}
Now you can use the data in the `$h` variable with other commands in the same se
are displayed on the local computer. For example: ```powershell
-Invoke-Command -Session $s {$h | where {$_.InstalledBy -ne "NTAUTHORITY\SYSTEM"}}
+Invoke-Command -Session $s {$h | where {$_.InstalledBy -ne "NT AUTHORITY\SYSTEM"}}
``` ### Advanced Remoting
samples Manipulating Items Directly https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/docs-conceptual/samples/Manipulating-Items-Directly.md
keywords: powershell,cmdlet
Title: Manipulating Items Directly description: PowerShell provides several cmdlets that help manage items on local and remote computers. Items are objects exposed by PowerShell providers like the file system, registry, certificates, and others. ---
-# Manipulating Items Directly
+# Manipulating items directly
-The elements that you see in Windows PowerShell drives, such as the files and folders in the file system drives, and the registry keys in the Windows PowerShell registry drives, are called *items* in Windows PowerShell. The cmdlets for working with them item have the noun **Item** in their names.
+The elements that you see in Windows PowerShell drives, such as the files and folders in the file
+system drives, and the registry keys in the Windows PowerShell registry drives, are called **items**
+in Windows PowerShell. The cmdlets for working with them item have the noun **Item** in their names.
-The output of the **Get-Command -Noun Item** command shows that there are nine Windows PowerShell item cmdlets.
+The output of the `Get-Command -Noun Item` command shows that there are nine PowerShell item
+cmdlets.
+```powershell
+Get-Command -Noun Item
```
-PS> Get-Command -Noun Item
+```Output
CommandType Name Definition ----------- ---- ---------- Cmdlet Clear-Item Clear-Item [-Path] <String[]...
Cmdlet Rename-Item Rename-Item [-Path] <String>...
Cmdlet Set-Item Set-Item [-Path] <String[]> ... ```
-## Creating New Items (New-Item)
+## Creating new Items (New-Item)
-To create a new item in the file system, use the **New-Item** cmdlet. Include the **Path** parameter with path to the item, and the **ItemType** parameter with a value of "file" or "directory".
+To create a new item in the file system, use the `New-Item` cmdlet. Include the **Path** parameter
+with path to the item, and the **ItemType** parameter with a value of `file` or `directory`.
-For example, to create a new directory named "New.Directory"in the C:\\Temp directory, type:
+For example, to create a new directory named `New.Directory` in the `C:\Temp` directory, type:
+```powershell
+New-Item -Path c:\temp\New.Directory -ItemType Directory
```
-PS> New-Item -Path c:\temp\New.Directory -ItemType Directory
+```Output
Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp Mode LastWriteTime Length Name
Mode LastWriteTime Length Name
d---- 2006-05-18 11:29 AM New.Directory ```
-To create a file, change the value of the **ItemType** parameter to "file". For example, to create a file named "file1.txt" in the New.Directory directory, type:
+To create a file, change the value of the **ItemType** parameter to `file`. For example, to create a
+file named `file1.txt` in the `New.Directory` directory, type:
+```powershell
+New-Item -Path C:\temp\New.Directory\file1.txt -ItemType file
```
-PS> New-Item -Path C:\temp\New.Directory\file1.txt -ItemType file
+```Output
Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp\New.Directory Mode LastWriteTime Length Name
Mode LastWriteTime Length Name
-a--- 2006-05-18 11:44 AM 0 file1 ```
-You can use the same technique to create a new registry key. In fact, a registry key is easier to create because the only item type in the Windows registry is a key. (Registry entries are item *properties*.) For example, to create a key named "_Test" in the CurrentVersion subkey, type:
+You can use the same technique to create a new registry key. In fact, a registry key is easier to
+create because the only item type in the Windows registry is a key. (Registry entries are item
+**properties**.) For example, to create a key named "_Test" in the CurrentVersion subkey, type:
+```powershell
+New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\_Test
```
-PS> New-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion_Test
- Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Micros
-oft\Windows\CurrentVersion
+```Output
+ Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
SKC VC Name Property --- -- ---- -------- 0 0 _Test {} ```
-When typing a registry path, be sure to include the colon (**:**) in the Windows PowerShell drive names, HKLM: and HKCU:. Without the colon, Windows PowerShell does not recognize the drive name in the path.
+When typing a registry path, be sure to include the colon (`:`) in the PowerShell drive
+names, `HKLM:` and `HKCU:`. Without the colon, PowerShell does not recognize the drive name in
+the path.
## Why Registry Values are not Items
-When you use the **Get-ChildItem** cmdlet to find the items in a registry key, you will never see actual registry entries or their values.
+When you use the `Get-ChildItem` cmdlet to find the items in a registry key, you will never see
+actual registry entries or their values.
-For example, the registry key **HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run** usually contains several registry entries that represent applications that run when the system starts.
+For example, the registry key `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run`
+usually contains several registry entries that represent applications that run when the system
+starts.
-However, when you use **Get-ChildItem** to look for child items in the key, all you will see is the **OptionalComponents** subkey of the key:
+However, when you use `Get-ChildItem` to look for child items in the key, all you will see is the
+**OptionalComponents** subkey of the key:
+```powershell
+Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Run
```
-PS> Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Run
- Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Micros
-oft\Windows\CurrentVersion\Run
+```Output
+ Hive: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
SKC VC Name Property --- -- ---- -------- 3 0 OptionalComponents {} ```
-Although it would be convenient to treat registry entries as items, you cannot specify a path to a registry entry in a way that ensures that it is unique. The path notation does not distinguish between the registry subkey named **Run** and the **(Default)** registry entry in the **Run** subkey. Furthermore, because registry entry names can contain the backslash character (**\\**), if registry entries were items, then you could not use the path notation to distinguish a registry entry named **Windows\\CurrentVersion\\Run** from the subkey that is located in that path.
+Although it would be convenient to treat registry entries as items, you cannot specify a path to a
+registry entry in a way that ensures that it is unique. The path notation does not distinguish
+between the registry subkey named **Run** and the **(Default)** registry entry in the **Run**
+subkey. Furthermore, because registry entry names can contain the backslash character (`\`), if
+registry entries were items, then you could not use the path notation to distinguish a registry
+entry named `Windows\CurrentVersion\Run` from the subkey that is located in that path.
-## Renaming Existing Items (Rename-Item)
+## Renaming existing Items (Rename-Item)
-To change the name of a file or folder, use the **Rename-Item** cmdlet. The following command changes the name of the **file1.txt** file to **fileOne.txt**.
+To change the name of a file or folder, use the `Rename-Item` cmdlet. The following command
+changes the name of the `file1.txt` file to `fileOne.txt`.
```powershell Rename-Item -Path C:\temp\New.Directory\file1.txt fileOne.txt ```
-The **Rename-Item** cmdlet can change the name of a file or a folder, but it cannot move an item. The following command fails because it attempts to move the file from the New.Directory directory to the Temp directory.
+The `Rename-Item` cmdlet can change the name of a file or a folder, but it cannot move an item. The
+following command fails because it attempts to move the file from the `New.Directory` directory to
+the Temp directory.
+```powershell
+Rename-Item -Path C:\temp\New.Directory\fileOne.txt c:\temp\fileOne.txt
```
-PS> Rename-Item -Path C:\temp\New.Directory\fileOne.txt c:\temp\fileOne.txt
+
+```Output
Rename-Item : Cannot rename because the target specified is not a path. At line:1 char:12 + Rename-Item <<<< -Path C:\temp\New.Directory\fileOne c:\temp\fileOne.txt
At line:1 char:12
## Moving Items (Move-Item)
-To move a file or folder, use the **Move-Item** cmdlet.
+To move a file or folder, use the `Move-Item` cmdlet.
-For example, the following command moves the New.Directory directory from the C:\\temp directory to the root of the C: drive. To verify that the item was moved, include the **PassThru** parameter of the **Move-Item** cmdlet. Without **Passthru**, the **Move-Item** cmdlet does not display any results.
+For example, the following command moves the New.Directory directory from the `C:\temp` directory to
+the root of the C: drive. To verify that the item was moved, include the **PassThru** parameter of
+the `Move-Item` cmdlet. Without **Passthru**, the `Move-Item` cmdlet does not display any
+results.
+```powershell
+Move-Item -Path C:\temp\New.Directory -Destination C:\ -PassThru
```
-PS> Move-Item -Path C:\temp\New.Directory -Destination C:\ -PassThru
+```Output
Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\ Mode LastWriteTime Length Name
d---- 2006-05-18 12:14 PM New.Directory
## Copying Items (Copy-Item)
-If you are familiar with the copy operations in other shells, you might find the behavior of the **Copy-Item** cmdlet in Windows PowerShell to be unusual. When you copy an item from one location to another, Copy-Item does not copy its contents by default.
+If you are familiar with the copy operations in other shells, you might find the behavior of the
+`Copy-Item` cmdlet in Windows PowerShell to be unusual. When you copy an item from one location to
+another, Copy-Item does not copy its contents by default.
-For example, if you copy the **New.Directory** directory from the C: drive to the C:\\temp directory, the command succeeds, but the files in the New.Directory directory are not copied.
+For example, if you copy the `New.Directory` directory from the C: drive to the `C:\temp`
+directory, the command succeeds, but the files in the New.Directory directory are not copied.
```powershell Copy-Item -Path C:\New.Directory -Destination C:\temp ```
-If you display the contents of **C:\\temp\\New.Directory**, you will find that it contains no files:
+If you display the contents of `C:\temp\New.Directory`, you will find that it contains no files:
``` PS> Get-ChildItem -Path C:\temp\New.Directory PS> ```
-Why doesn't the **Copy-Item** cmdlet copy the contents to the new location?
+Why doesn't the `Copy-Item` cmdlet copy the contents to the new location?
-The **Copy-Item** cmdlet was designed to be generic; it is not just for copying files and folders. Also, even when copying files and folders, you might want to copy only the container and not the items within it.
+The `Copy-Item` cmdlet was designed to be generic; it is not just for copying files and folders.
+Also, even when copying files and folders, you might want to copy only the container and not the
+items within it.
-To copy all of the contents of a folder, include the **Recurse** parameter of the **Copy-Item** cmdlet in the command. If you have already copied the directory without its contents, add the **Force** parameter, which allows you to overwrite the empty folder.
+To copy all of the contents of a folder, include the **Recurse** parameter of the `Copy-Item`
+cmdlet in the command. If you have already copied the directory without its contents, add the
+**Force** parameter, which allows you to overwrite the empty folder.
+```powershell
+Copy-Item -Path C:\New.Directory -Destination C:\temp -Recurse -Force -Passthru
```
-PS> Copy-Item -Path C:\New.Directory -Destination C:\temp -Recurse -Force -Passthru
+```Output
Directory: Microsoft.Windows PowerShell.Core\FileSystem::C:\temp Mode LastWriteTime Length Name
Mode LastWriteTime Length Name
## Deleting Items (Remove-Item)
-To delete files and folders, use the **Remove-Item** cmdlet. Windows PowerShell cmdlets, such as **Remove-Item**, that can make significant, irreversible changes will often prompt for confirmation when you enter its commands. For example, if you try to remove the **New.Directory** folder, you will be prompted to confirm the command, because the folder contains files:
+To delete files and folders, use the `Remove-Item` cmdlet. Windows PowerShell cmdlets, such as
+`Remove-Item`, that can make significant, irreversible changes will often prompt for confirmation
+when you enter its commands. For example, if you try to remove the `New.Directory` folder, you
+will be prompted to confirm the command, because the folder contains files:
+```powershell
+Remove-Item C:\New.Directory
```
-PS> Remove-Item C:\New.Directory
+```Output
Confirm The item at C:\temp\New.Directory has children and the -recurse parameter was not specified. If you continue, all children will be removed with the item. Are you
specified. If you continue, all children will be removed with the item. Are you
(default is "Y"): ```
-Because **Yes** is the default response, to delete the folder and its files, press the **Enter** key. To remove the folder without confirming, use the **-Recurse** parameter.
+Because `Yes` is the default response, to delete the folder and its files, press the <kbd>Enter</kbd>
+key. To remove the folder without confirming, use the **Recurse** parameter.
```powershell Remove-Item C:\temp\New.Directory -Recurse
Remove-Item C:\temp\New.Directory -Recurse
## Executing Items (Invoke-Item)
-Windows PowerShell uses the **Invoke-Item** cmdlet to perform a default action for a file or folder. This default action is determined by the default application handler in the registry; the effect is the same as if you double-click the item in File Explorer.
+PowerShell uses the `Invoke-Item` cmdlet to perform a default action for a file or folder.
+This default action is determined by the default application handler in the registry; the effect is
+the same as if you double-click the item in File Explorer.
For example, suppose you run the following command:
For example, suppose you run the following command:
Invoke-Item C:\WINDOWS ```
-An Explorer window that is located in C:\\Windows appears, just as if you had double-clicked the C:\\Windows folder.
+An Explorer window that is located in `C:\Windows` appears, just as if you had double-clicked the
+`C:\Windows` folder.
-If you invoke the **Boot.ini** file on a system prior to Windows Vista:
+If you invoke the `Boot.ini` file on a system prior to Windows Vista:
```powershell Invoke-Item C:\boot.ini ```
-If the .ini file type is associated with Notepad, the boot.ini file opens in Notepad.
+If the `.ini` file type is associated with Notepad, the `boot.ini` file opens in Notepad.