diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index e69c1f5ab1d0..8057f6b2599f 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,20 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION +## Short description -Variables that customize the behavior of PowerShell +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -23,127 +24,127 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = ASCIIEncoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumAliasCount` | 4096 | +| `$MaximumDriveCount` | 4096 | +| `$MaximumErrorCount` | 256 | +| `$MaximumFunctionCount` | 4096 | +| `$MaximumHistoryCount` | 4096 | +| `$MaximumVariableCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | ASCIIEncoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all Windows PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how Windows PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION - -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. +#### Detailed explanation -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". @@ -151,33 +152,46 @@ Performing operation "Remove File" on Target "C:\file.txt". [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` + +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". @@ -186,76 +200,84 @@ Performing operation "Remove File" on Target "C:\temp2.txt". ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The user is prompted +for confirmation. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? @@ -263,403 +285,435 @@ Continue with this operation? [?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +```Output +DEBUG: Hello, World +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further +- **Continue**: (Default) Displays the error message and continues executing. +- **Suspend**: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +#### Examples -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -##### EXAMPLES +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. - -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - + [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): + [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -##### EXAMPLES +#### Examples -These example show the effect of the ErrorView values. - -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force +``` -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. +Find the current value of `$FormatEnumerationLimit`. ```powershell -PS> $formatenumerationlimit # Find the current value +$FormatEnumerationLimit +``` + +```Output 4 +``` -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. +```powershell +Get-Service | Group-Object -Property Status +``` -#### \$Log*Event +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} +``` -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. -The Log*Event preference variables are as follows: +```powershell +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status +``` -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... +``` -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). +Use `Format-Table` with the **Wrap** parameter to display the list of services. -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). +```powershell +Get-Service | Group-Object -Property Status | Format-Table -Wrap +``` -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} +``` -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). +### \$InformationPreference -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts. If the **InformationAction** +parameter is used, its value overrides the value of the +`$InformationPreference` variable. -To enable a Log*Event, type the variable with a value of \$true, for example: +The valid values are as follows: -```powershell -$LogCommandLifeCycleEvent -``` +- **Stop**: Stops a command or script. +- **Inquire**: Displays the informational message that you specify, then asks + whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **Suspend**: Automatically suspends a workflow job to allow users to see the + messages before continuing. The workflow can be resumed at the user's + discretion. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. -- or - +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell $LogCommandLifeCycleEvent = $true ``` -To disable an event type, type the variable with a value of \$false, for +To disable an event type, type the variable with a value of `$false`, for example: ```powershell @@ -667,18 +721,18 @@ $LogCommandLifeCycleEvent = $false ``` The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -#### \$MaximumAliasCount +### \$MaximumAliasCount Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. +value is **4096** and that should be enough for most uses. You can adjust +`$MaximumAliasCount` to meet your needs. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -686,15 +740,15 @@ To count the aliases on your system, type: (Get-Alias).count ``` -#### \$MaximumDriveCount +### \$MaximumDriveCount -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. +Determines how many PowerShell drives are permitted in a given session. For +example, file system drives and data stores that are exposed by PowerShell +providers and appear as drives, such as the `Alias:` and `HKLM:` drives. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -702,28 +756,27 @@ To count the aliases on your system, type: (Get-PSDrive).count ``` -#### \$MaximumErrorCount +### \$MaximumErrorCount Determines how many errors are saved in the error history for the session. -Valid values: 256 - 32768 (Int32) +**Valid values**: 256 - 32768 (`Int32`) -Default: 256 +**Default**: 256 -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). +Objects that represent each retained error are stored in the `$Error` automatic +variable. `$Error` contains an array of error record objects. The most recent +error is the first object in the array, `$Error[0]`. -To count the errors on your system, use the Count property of the \$Error -array. Type: +To count the errors on your system, use the `$Error` array's **Count** +property. ```powershell $Error.count ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: +To display a specific error, use the `[0]` array notation to see the most +recent error. ```powershell $Error[0] @@ -735,376 +788,368 @@ To display the oldest retained error, type: $Error[($Error.Count -1] ``` -To display the properties of the ErrorRecord object, type: +The **Force** parameter overrides the special formatting of **ErrorRecord** +objects and reverts to the conventional format. To display the properties of +the **ErrorRecord** object, type the following command: ```powershell -$Error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. - -To delete all errors from the error history, use the Clear method of the error -array. +In this example, `$Error.Count` displays the number of errors. To delete all +errors from the error history, use the `Clear` method of the error array. ```powershell -PS> $Error.count +$Error.Count +``` + +```Output 17 -PS> $Error.clear() -PS> -PS> $Error.count +``` + +```powershell +$Error.Clear() +$Error.Count +``` + +```Output 0 ``` -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. +To find all properties and methods of an error array, use the `Get-Member` +cmdlet with its **InputObject** parameter. When you use the **InputObject** +parameter, `Get-Member` displays the properties and methods of the collection. + +```powershell +Get-Member -InputObject $Error +``` + +When you pipe a collection of objects to `Get-Member`, `Get-Member` displays +the properties and methods of the objects in the collection. -#### \$MaximumFunctionCount +```powershell +$Error | Get-Member +``` + +### \$MaximumFunctionCount Determines how many functions are permitted in a given session. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). +To see the functions in your session, use the PowerShell `Function:` drive that +is exposed by the PowerShell `Function` provider. For more information about +the `Function` provider, [about_Function_Provider](about_Function_Provider.md). To list the functions in the current session, type: ```powershell -Get-ChildItem function: +Get-ChildItem Function: ``` To count the functions in the current session, type: ```powershell -(Get-ChildItem function:).count +(Get-ChildItem Function:).Count ``` -#### \$MaximumHistoryCount +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount +### \$MaximumVariableCount Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. +automatic variables, preference variables, and the variables that you create in +commands and scripts. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". +To see the variables in your session, use the `Get-Variable` cmdlet and the +features of the PowerShell `Variable:` drive and the PowerShell `Variable` +provider. For information, see [about_Variable_Provider](about_Variable_Provider.md). To find the current number of variables on the system, type: ```powershell -(Get-Variable).count +(Get-Variable).Count ``` -#### \$OFS +### \$OFS -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -Valid values: Any string. -Default: Space +**Valid values**: Any string. -By default, the \$OFS variable does not exist and the output file separator is -a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. - -For example: - -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 +**Default**: Space -2 +By default, the `$OFS` variable doesn't exist and the output file separator is +a space, but you can add this variable and set it to any string. You can change +the value of `$OFS` in your session, by typing `$OFS=""`. -3 +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -4 -``` - -##### EXAMPLES +#### Examples -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: ASCIIEncoding object (System.Text.ASCIIEncoding) +**Default**: ASCIIEncoding object (System.Text.ASCIIEncoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. - -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +session configuration that's located on the remote computer. -The default value: +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1129,226 +1174,274 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your Windows PowerShell profile. - -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` + +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue +``` + +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. + +```powershell +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m ``` -This example shows the effect of the SilentlyContinue value. +This example uses the **WarningAction** parameter to stop when a warning is +generated. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```Output WARNING: This action can delete data. Confirm @@ -1357,148 +1450,200 @@ Continue with this operation? [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Valid values: +The valid values are as follows: -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +#### Examples + +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt ``` -##### EXAMPLES +```powershell +Get-ChildItem -Path .\test.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +```powershell +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt +``` + +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Get-Process -Name Winword +``` + +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Stop-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) \ No newline at end of file +[about_Variables](about_Variables.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index 500c871d512a..0180786b8156 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,20 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION +## Short description -Variables that customize the behavior of PowerShell +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -23,127 +24,127 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = ASCIIEncoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumAliasCount` | 4096 | +| `$MaximumDriveCount` | 4096 | +| `$MaximumErrorCount` | 256 | +| `$MaximumFunctionCount` | 4096 | +| `$MaximumHistoryCount` | 4096 | +| `$MaximumVariableCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | ASCIIEncoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all Windows PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how Windows PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION - -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. +#### Detailed explanation -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". @@ -151,33 +152,46 @@ Performing operation "Remove File" on Target "C:\file.txt". [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` + +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". @@ -186,76 +200,84 @@ Performing operation "Remove File" on Target "C:\temp2.txt". ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The user is prompted +for confirmation. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? @@ -263,403 +285,435 @@ Continue with this operation? [?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +```Output +DEBUG: Hello, World +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further +- **Continue**: (Default) Displays the error message and continues executing. +- **Suspend**: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +#### Examples -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -##### EXAMPLES +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. - -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - + [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): + [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -##### EXAMPLES +#### Examples -These example show the effect of the ErrorView values. - -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force +``` -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. +Find the current value of `$FormatEnumerationLimit`. ```powershell -PS> $formatenumerationlimit # Find the current value +$FormatEnumerationLimit +``` + +```Output 4 +``` -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. +```powershell +Get-Service | Group-Object -Property Status +``` -#### \$Log*Event +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} +``` -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. -The Log*Event preference variables are as follows: +```powershell +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status +``` -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... +``` -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). +Use `Format-Table` with the **Wrap** parameter to display the list of services. -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). +```powershell +Get-Service | Group-Object -Property Status | Format-Table -Wrap +``` -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} +``` -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). +### \$InformationPreference -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts. If the **InformationAction** +parameter is used, its value overrides the value of the +`$InformationPreference` variable. -To enable a Log*Event, type the variable with a value of \$true, for example: +The valid values are as follows: -```powershell -$LogCommandLifeCycleEvent -``` +- **Stop**: Stops a command or script. +- **Inquire**: Displays the informational message that you specify, then asks + whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **Suspend**: Automatically suspends a workflow job to allow users to see the + messages before continuing. The workflow can be resumed at the user's + discretion. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. -- or - +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell $LogCommandLifeCycleEvent = $true ``` -To disable an event type, type the variable with a value of \$false, for +To disable an event type, type the variable with a value of `$false`, for example: ```powershell @@ -667,18 +721,18 @@ $LogCommandLifeCycleEvent = $false ``` The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -#### \$MaximumAliasCount +### \$MaximumAliasCount Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. +value is **4096** and that should be enough for most uses. You can adjust +`$MaximumAliasCount` to meet your needs. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -686,15 +740,15 @@ To count the aliases on your system, type: (Get-Alias).count ``` -#### \$MaximumDriveCount +### \$MaximumDriveCount -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. +Determines how many PowerShell drives are permitted in a given session. For +example, file system drives and data stores that are exposed by PowerShell +providers and appear as drives, such as the `Alias:` and `HKLM:` drives. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -702,28 +756,27 @@ To count the aliases on your system, type: (Get-PSDrive).count ``` -#### \$MaximumErrorCount +### \$MaximumErrorCount Determines how many errors are saved in the error history for the session. -Valid values: 256 - 32768 (Int32) +**Valid values**: 256 - 32768 (`Int32`) -Default: 256 +**Default**: 256 -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). +Objects that represent each retained error are stored in the `$Error` automatic +variable. `$Error` contains an array of error record objects. The most recent +error is the first object in the array, `$Error[0]`. -To count the errors on your system, use the Count property of the \$Error -array. Type: +To count the errors on your system, use the `$Error` array's **Count** +property. ```powershell $Error.count ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: +To display a specific error, use the `[0]` array notation to see the most +recent error. ```powershell $Error[0] @@ -735,376 +788,368 @@ To display the oldest retained error, type: $Error[($Error.Count -1] ``` -To display the properties of the ErrorRecord object, type: +The **Force** parameter overrides the special formatting of **ErrorRecord** +objects and reverts to the conventional format. To display the properties of +the **ErrorRecord** object, type the following command: ```powershell -$Error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. - -To delete all errors from the error history, use the Clear method of the error -array. +In this example, `$Error.Count` displays the number of errors. To delete all +errors from the error history, use the `Clear` method of the error array. ```powershell -PS> $Error.count +$Error.Count +``` + +```Output 17 -PS> $Error.clear() -PS> -PS> $Error.count +``` + +```powershell +$Error.Clear() +$Error.Count +``` + +```Output 0 ``` -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. +To find all properties and methods of an error array, use the `Get-Member` +cmdlet with its **InputObject** parameter. When you use the **InputObject** +parameter, `Get-Member` displays the properties and methods of the collection. + +```powershell +Get-Member -InputObject $Error +``` + +When you pipe a collection of objects to `Get-Member`, `Get-Member` displays +the properties and methods of the objects in the collection. -#### \$MaximumFunctionCount +```powershell +$Error | Get-Member +``` + +### \$MaximumFunctionCount Determines how many functions are permitted in a given session. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). +To see the functions in your session, use the PowerShell `Function:` drive that +is exposed by the PowerShell `Function` provider. For more information about +the `Function` provider, [about_Function_Provider](about_Function_Provider.md). To list the functions in the current session, type: ```powershell -Get-ChildItem function: +Get-ChildItem Function: ``` To count the functions in the current session, type: ```powershell -(Get-ChildItem function:).count +(Get-ChildItem Function:).Count ``` -#### \$MaximumHistoryCount +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount +### \$MaximumVariableCount Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. +automatic variables, preference variables, and the variables that you create in +commands and scripts. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". +To see the variables in your session, use the `Get-Variable` cmdlet and the +features of the PowerShell `Variable:` drive and the PowerShell `Variable` +provider. For information, see [about_Variable_Provider](about_Variable_Provider.md). To find the current number of variables on the system, type: ```powershell -(Get-Variable).count +(Get-Variable).Count ``` -#### \$OFS +### \$OFS -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -Valid values: Any string. -Default: Space +**Valid values**: Any string. -By default, the \$OFS variable does not exist and the output file separator is -a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. - -For example: - -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 +**Default**: Space -2 +By default, the `$OFS` variable doesn't exist and the output file separator is +a space, but you can add this variable and set it to any string. You can change +the value of `$OFS` in your session, by typing `$OFS=""`. -3 +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -4 -``` - -##### EXAMPLES +#### Examples -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: ASCIIEncoding object (System.Text.ASCIIEncoding) +**Default**: ASCIIEncoding object (System.Text.ASCIIEncoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. - -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +session configuration that's located on the remote computer. -The default value: +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1129,226 +1174,274 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your Windows PowerShell profile. - -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` + +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue +``` + +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. + +```powershell +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m ``` -This example shows the effect of the SilentlyContinue value. +This example uses the **WarningAction** parameter to stop when a warning is +generated. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```Output WARNING: This action can delete data. Confirm @@ -1357,148 +1450,200 @@ Continue with this operation? [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Valid values: +The valid values are as follows: -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +#### Examples + +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt ``` -##### EXAMPLES +```powershell +Get-ChildItem -Path .\test.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +```powershell +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt +``` + +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Get-Process -Name Winword +``` + +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Stop-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) \ No newline at end of file +[about_Variables](about_Variables.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index 500c871d512a..987b88611c8e 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,20 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION +## Short description -Variables that customize the behavior of PowerShell +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -23,127 +24,127 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = ASCIIEncoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumAliasCount` | 4096 | +| `$MaximumDriveCount` | 4096 | +| `$MaximumErrorCount` | 256 | +| `$MaximumFunctionCount` | 4096 | +| `$MaximumHistoryCount` | 4096 | +| `$MaximumVariableCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | ASCIIEncoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all Windows PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how Windows PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION - -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. +#### Detailed explanation -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". @@ -151,33 +152,46 @@ Performing operation "Remove File" on Target "C:\file.txt". [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` + +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". @@ -186,76 +200,84 @@ Performing operation "Remove File" on Target "C:\temp2.txt". ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The user is prompted +for confirmation. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? @@ -263,403 +285,438 @@ Continue with this operation? [?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +```Output +DEBUG: Hello, World +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further +- **Continue**: (Default) Displays the error message and continues executing. +- **Suspend**: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +#### Examples -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -##### EXAMPLES +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. - -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - + [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): + [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. - -##### EXAMPLES +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -These example show the effect of the ErrorView values. +#### Examples -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force +``` -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. +Find the current value of `$FormatEnumerationLimit`. ```powershell -PS> $formatenumerationlimit # Find the current value -4 - -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. - - -#### \$Log*Event - -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. +$FormatEnumerationLimit +``` -The Log*Event preference variables are as follows: +```Output +4 +``` -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). +```powershell +Get-Service | Group-Object -Property Status +``` -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} +``` -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). +```powershell +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status +``` -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... +``` -To enable a Log*Event, type the variable with a value of \$true, for example: +Use `Format-Table` with the **Wrap** parameter to display the list of services. ```powershell -$LogCommandLifeCycleEvent +Get-Service | Group-Object -Property Status | Format-Table -Wrap +``` + +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} ``` -- or - +### \$InformationPreference + +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts by adding the [Write-Information](../../Microsoft.PowerShell.Utility/Write-Information.md) +cmdlet. If the **InformationAction** parameter is used, its value overrides the +value of the `$InformationPreference` variable. `Write-Information` was +introduced in PowerShell 5.0. + +The valid values are as follows: + +- **Stop**: Stops a command or script at an occurrence of the + `Write-Information` command. +- **Inquire**: Displays the informational message that you specify in a + `Write-Information` command, then asks whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **Suspend**: Automatically suspends a workflow job after a + `Write-Information` command is carried out, to allow users to see the + messages before continuing. The workflow can be resumed at the user's + discretion. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. + +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell $LogCommandLifeCycleEvent = $true ``` -To disable an event type, type the variable with a value of \$false, for +To disable an event type, type the variable with a value of `$false`, for example: ```powershell @@ -667,18 +724,18 @@ $LogCommandLifeCycleEvent = $false ``` The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -#### \$MaximumAliasCount +### \$MaximumAliasCount Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. +value is **4096** and that should be enough for most uses. You can adjust +`$MaximumAliasCount` to meet your needs. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -686,15 +743,15 @@ To count the aliases on your system, type: (Get-Alias).count ``` -#### \$MaximumDriveCount +### \$MaximumDriveCount -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. +Determines how many PowerShell drives are permitted in a given session. For +example, file system drives and data stores that are exposed by PowerShell +providers and appear as drives, such as the `Alias:` and `HKLM:` drives. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -702,28 +759,27 @@ To count the aliases on your system, type: (Get-PSDrive).count ``` -#### \$MaximumErrorCount +### \$MaximumErrorCount Determines how many errors are saved in the error history for the session. -Valid values: 256 - 32768 (Int32) +**Valid values**: 256 - 32768 (`Int32`) -Default: 256 +**Default**: 256 -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). +Objects that represent each retained error are stored in the `$Error` automatic +variable. `$Error` contains an array of error record objects. The most recent +error is the first object in the array, `$Error[0]`. -To count the errors on your system, use the Count property of the \$Error -array. Type: +To count the errors on your system, use the `$Error` array's **Count** +property. ```powershell $Error.count ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: +To display a specific error, use the `[0]` array notation to see the most +recent error. ```powershell $Error[0] @@ -735,376 +791,368 @@ To display the oldest retained error, type: $Error[($Error.Count -1] ``` -To display the properties of the ErrorRecord object, type: +The **Force** parameter overrides the special formatting of **ErrorRecord** +objects and reverts to the conventional format. To display the properties of +the **ErrorRecord** object, type the following command: ```powershell -$Error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. - -To delete all errors from the error history, use the Clear method of the error -array. +In this example, `$Error.Count` displays the number of errors. To delete all +errors from the error history, use the `Clear` method of the error array. ```powershell -PS> $Error.count +$Error.Count +``` + +```Output 17 -PS> $Error.clear() -PS> -PS> $Error.count +``` + +```powershell +$Error.Clear() +$Error.Count +``` + +```Output 0 ``` -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. +To find all properties and methods of an error array, use the `Get-Member` +cmdlet with its **InputObject** parameter. When you use the **InputObject** +parameter, `Get-Member` displays the properties and methods of the collection. + +```powershell +Get-Member -InputObject $Error +``` + +When you pipe a collection of objects to `Get-Member`, `Get-Member` displays +the properties and methods of the objects in the collection. + +```powershell +$Error | Get-Member +``` -#### \$MaximumFunctionCount +### \$MaximumFunctionCount Determines how many functions are permitted in a given session. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). +To see the functions in your session, use the PowerShell `Function:` drive that +is exposed by the PowerShell `Function` provider. For more information about +the `Function` provider, [about_Function_Provider](about_Function_Provider.md). To list the functions in the current session, type: ```powershell -Get-ChildItem function: +Get-ChildItem Function: ``` To count the functions in the current session, type: ```powershell -(Get-ChildItem function:).count +(Get-ChildItem Function:).Count ``` -#### \$MaximumHistoryCount +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount +### \$MaximumVariableCount Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. +automatic variables, preference variables, and the variables that you create in +commands and scripts. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". +To see the variables in your session, use the `Get-Variable` cmdlet and the +features of the PowerShell `Variable:` drive and the PowerShell `Variable` +provider. For information, see [about_Variable_Provider](about_Variable_Provider.md). To find the current number of variables on the system, type: ```powershell -(Get-Variable).count +(Get-Variable).Count ``` -#### \$OFS - -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. +### \$OFS -Valid values: Any string. -Default: Space +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -By default, the \$OFS variable does not exist and the output file separator is -a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. - -For example: - -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 +**Valid values**: Any string. -2 +**Default**: Space -3 +By default, the `$OFS` variable doesn't exist and the output file separator is +a space, but you can add this variable and set it to any string. You can change +the value of `$OFS` in your session, by typing `$OFS=""`. -4 -``` +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -##### EXAMPLES +#### Examples -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: ASCIIEncoding object (System.Text.ASCIIEncoding) +**Default**: ASCIIEncoding object (System.Text.ASCIIEncoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. +session configuration that's located on the remote computer. -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -The default value: - -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1129,226 +1177,274 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your Windows PowerShell profile. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). - -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue +``` + +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +```powershell +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m ``` -This example shows the effect of the SilentlyContinue value. +This example uses the **WarningAction** parameter to stop when a warning is +generated. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```Output WARNING: This action can delete data. Confirm @@ -1357,148 +1453,200 @@ Continue with this operation? [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Valid values: +The valid values are as follows: -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +#### Examples + +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt ``` -##### EXAMPLES +```powershell +Get-ChildItem -Path .\test.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +```Output + Directory: C:\Test -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. + +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt +``` -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. + +```powershell +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt +``` + +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Get-Process -Name Winword +``` + +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Stop-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) \ No newline at end of file +[about_Variables](about_Variables.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index 902ff4b5d54a..987b88611c8e 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,19 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION -Variables that customize the behavior of PowerShell +## Short description + +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -22,127 +24,127 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = ASCIIEncoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumAliasCount` | 4096 | +| `$MaximumDriveCount` | 4096 | +| `$MaximumErrorCount` | 256 | +| `$MaximumFunctionCount` | 4096 | +| `$MaximumHistoryCount` | 4096 | +| `$MaximumVariableCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | ASCIIEncoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION +#### Detailed explanation -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. - -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". @@ -150,33 +152,46 @@ Performing operation "Remove File" on Target "C:\file.txt". [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` + +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". @@ -185,76 +200,84 @@ Performing operation "Remove File" on Target "C:\temp2.txt". ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The user is prompted +for confirmation. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? @@ -262,403 +285,438 @@ Continue with this operation? [?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +```Output +DEBUG: Hello, World +``` -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further +- **Continue**: (Default) Displays the error message and continues executing. +- **Suspend**: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +#### Examples -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -##### EXAMPLES +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. - -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - + [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): + [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. - -##### EXAMPLES +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -These example show the effect of the ErrorView values. +#### Examples -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force +``` -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. +Find the current value of `$FormatEnumerationLimit`. ```powershell -PS> $formatenumerationlimit # Find the current value -4 - -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. - - -#### \$Log*Event - -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. +$FormatEnumerationLimit +``` -The Log*Event preference variables are as follows: +```Output +4 +``` -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). +```powershell +Get-Service | Group-Object -Property Status +``` -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} +``` -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). +```powershell +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status +``` -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... +``` -To enable a Log*Event, type the variable with a value of \$true, for example: +Use `Format-Table` with the **Wrap** parameter to display the list of services. ```powershell -$LogCommandLifeCycleEvent +Get-Service | Group-Object -Property Status | Format-Table -Wrap +``` + +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} ``` -- or - +### \$InformationPreference + +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts by adding the [Write-Information](../../Microsoft.PowerShell.Utility/Write-Information.md) +cmdlet. If the **InformationAction** parameter is used, its value overrides the +value of the `$InformationPreference` variable. `Write-Information` was +introduced in PowerShell 5.0. + +The valid values are as follows: + +- **Stop**: Stops a command or script at an occurrence of the + `Write-Information` command. +- **Inquire**: Displays the informational message that you specify in a + `Write-Information` command, then asks whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **Suspend**: Automatically suspends a workflow job after a + `Write-Information` command is carried out, to allow users to see the + messages before continuing. The workflow can be resumed at the user's + discretion. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. + +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell $LogCommandLifeCycleEvent = $true ``` -To disable an event type, type the variable with a value of \$false, for +To disable an event type, type the variable with a value of `$false`, for example: ```powershell @@ -666,18 +724,18 @@ $LogCommandLifeCycleEvent = $false ``` The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -#### \$MaximumAliasCount +### \$MaximumAliasCount Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. +value is **4096** and that should be enough for most uses. You can adjust +`$MaximumAliasCount` to meet your needs. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -685,15 +743,15 @@ To count the aliases on your system, type: (Get-Alias).count ``` -#### \$MaximumDriveCount +### \$MaximumDriveCount -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. +Determines how many PowerShell drives are permitted in a given session. For +example, file system drives and data stores that are exposed by PowerShell +providers and appear as drives, such as the `Alias:` and `HKLM:` drives. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 To count the aliases on your system, type: @@ -701,28 +759,27 @@ To count the aliases on your system, type: (Get-PSDrive).count ``` -#### \$MaximumErrorCount +### \$MaximumErrorCount Determines how many errors are saved in the error history for the session. -Valid values: 256 - 32768 (Int32) +**Valid values**: 256 - 32768 (`Int32`) -Default: 256 +**Default**: 256 -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). +Objects that represent each retained error are stored in the `$Error` automatic +variable. `$Error` contains an array of error record objects. The most recent +error is the first object in the array, `$Error[0]`. -To count the errors on your system, use the Count property of the \$Error -array. Type: +To count the errors on your system, use the `$Error` array's **Count** +property. ```powershell $Error.count ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: +To display a specific error, use the `[0]` array notation to see the most +recent error. ```powershell $Error[0] @@ -734,376 +791,368 @@ To display the oldest retained error, type: $Error[($Error.Count -1] ``` -To display the properties of the ErrorRecord object, type: +The **Force** parameter overrides the special formatting of **ErrorRecord** +objects and reverts to the conventional format. To display the properties of +the **ErrorRecord** object, type the following command: ```powershell -$Error[0] | Format-List -Property * -force +$Error[0] | Format-List -Property * -Force ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. - -To delete all errors from the error history, use the Clear method of the error -array. +In this example, `$Error.Count` displays the number of errors. To delete all +errors from the error history, use the `Clear` method of the error array. ```powershell -PS> $Error.count +$Error.Count +``` + +```Output 17 -PS> $Error.clear() -PS> -PS> $Error.count +``` + +```powershell +$Error.Clear() +$Error.Count +``` + +```Output 0 ``` -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. +To find all properties and methods of an error array, use the `Get-Member` +cmdlet with its **InputObject** parameter. When you use the **InputObject** +parameter, `Get-Member` displays the properties and methods of the collection. + +```powershell +Get-Member -InputObject $Error +``` -#### \$MaximumFunctionCount +When you pipe a collection of objects to `Get-Member`, `Get-Member` displays +the properties and methods of the objects in the collection. + +```powershell +$Error | Get-Member +``` + +### \$MaximumFunctionCount Determines how many functions are permitted in a given session. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). +To see the functions in your session, use the PowerShell `Function:` drive that +is exposed by the PowerShell `Function` provider. For more information about +the `Function` provider, [about_Function_Provider](about_Function_Provider.md). To list the functions in the current session, type: ```powershell -Get-ChildItem function: +Get-ChildItem Function: ``` To count the functions in the current session, type: ```powershell -(Get-ChildItem function:).count +(Get-ChildItem Function:).Count ``` -#### \$MaximumHistoryCount +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount +### \$MaximumVariableCount Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. +automatic variables, preference variables, and the variables that you create in +commands and scripts. -Valid values: 1024 - 32768 (Int32) +**Valid values**: 1024 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". +To see the variables in your session, use the `Get-Variable` cmdlet and the +features of the PowerShell `Variable:` drive and the PowerShell `Variable` +provider. For information, see [about_Variable_Provider](about_Variable_Provider.md). To find the current number of variables on the system, type: ```powershell -(Get-Variable).count +(Get-Variable).Count ``` -#### \$OFS - -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. +### \$OFS -Valid values: Any string. -Default: Space +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -By default, the \$OFS variable does not exist and the output file separator is -a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. - -For example: - -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 +**Valid values**: Any string. -2 +**Default**: Space -3 +By default, the `$OFS` variable doesn't exist and the output file separator is +a space, but you can add this variable and set it to any string. You can change +the value of `$OFS` in your session, by typing `$OFS=""`. -4 -``` +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -##### EXAMPLES +#### Examples -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: ASCIIEncoding object (System.Text.ASCIIEncoding) +**Default**: ASCIIEncoding object (System.Text.ASCIIEncoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. +session configuration that's located on the remote computer. -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -The default value: - -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1128,226 +1177,274 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your PowerShell profile. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). - -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue +``` + +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +```powershell +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m ``` -This example shows the effect of the SilentlyContinue value. +This example uses the **WarningAction** parameter to stop when a warning is +generated. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```Output WARNING: This action can delete data. Confirm @@ -1356,148 +1453,200 @@ Continue with this operation? [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Valid values: +The valid values are as follows: -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +#### Examples + +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt ``` -##### EXAMPLES +```powershell +Get-ChildItem -Path .\test.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +```Output + Directory: C:\Test -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. + +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt +``` -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. + +```powershell +Get-ChildItem -Path .\test2.txt +``` + +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt +``` + +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Get-Process -Name Winword +``` + +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Stop-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) \ No newline at end of file +[about_Variables](about_Variables.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/6/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index 4feac8b00f86..33483a12d969 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,19 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION -Variables that customize the behavior of PowerShell +## Short description + +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -22,127 +24,122 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = UTF8Encoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumHistoryCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | UTF8Encoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION - -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. +#### Detailed explanation -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". @@ -150,33 +147,46 @@ Performing operation "Remove File" on Target "C:\file.txt". [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. + +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". @@ -185,925 +195,803 @@ Performing operation "Remove File" on Target "C:\temp2.txt". ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The debug message is displayed. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World -Confirm -Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` + +```Output +DEBUG: Hello, World +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further +- **Continue**: (Default) Displays the error message and continues executing. +- **Suspend**: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. - -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +#### Examples -##### EXAMPLES +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - + [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): + [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. - -##### EXAMPLES +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -These example show the effect of the ErrorView values. +#### Examples -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force - -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +$Error[0] | Format-List -Property * -Force +``` + +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. - -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. - -```powershell -PS> $formatenumerationlimit # Find the current value -4 - -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. - - -#### \$Log*Event - -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. - -The Log*Event preference variables are as follows: - -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). - -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). - -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). - -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). - -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). - -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". - -To enable a Log*Event, type the variable with a value of \$true, for example: +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -```powershell -$LogCommandLifeCycleEvent -``` - -- or - +Find the current value of `$FormatEnumerationLimit`. ```powershell -$LogCommandLifeCycleEvent = $true +$FormatEnumerationLimit ``` -To disable an event type, type the variable with a value of \$false, for -example: - -```powershell -$LogCommandLifeCycleEvent = $false +```Output +4 ``` -The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. - -#### \$MaximumAliasCount - -Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To count the aliases on your system, type: +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. ```powershell -(Get-Alias).count +Get-Service | Group-Object -Property Status ``` -#### \$MaximumDriveCount - -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To count the aliases on your system, type: - -```powershell -(Get-PSDrive).count +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} ``` -#### \$MaximumErrorCount - -Determines how many errors are saved in the error history for the session. - -Valid values: 256 - 32768 (Int32) - -Default: 256 - -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). - -To count the errors on your system, use the Count property of the \$Error -array. Type: +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. ```powershell -$Error.count +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: - -```powershell -$Error[0] +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... ``` -To display the oldest retained error, type: +Use `Format-Table` with the **Wrap** parameter to display the list of services. ```powershell -$Error[($Error.Count -1] +Get-Service | Group-Object -Property Status | Format-Table -Wrap ``` -To display the properties of the ErrorRecord object, type: - -```powershell -$Error[0] | Format-List -Property * -force +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. +### \$InformationPreference + +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts by adding the [Write-Information](../../Microsoft.PowerShell.Utility/Write-Information.md) +cmdlet. If the **InformationAction** parameter is used, its value overrides the +value of the `$InformationPreference` variable. `Write-Information` was +introduced in PowerShell 5.0. + +The valid values are as follows: + +- **Stop**: Stops a command or script at an occurrence of the + `Write-Information` command. +- **Inquire**: Displays the informational message that you specify in a + `Write-Information` command, then asks whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **Suspend**: Automatically suspends a workflow job after a + `Write-Information` command is carried out, to allow users to see the + messages before continuing. The workflow can be resumed at the user's + discretion. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. -To delete all errors from the error history, use the Clear method of the error -array. +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell -PS> $Error.count -17 -PS> $Error.clear() -PS> -PS> $Error.count -0 +$LogCommandLifeCycleEvent = $true ``` -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. - -#### \$MaximumFunctionCount - -Determines how many functions are permitted in a given session. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). - -To list the functions in the current session, type: +To disable an event type, type the variable with a value of `$false`, for +example: ```powershell -Get-ChildItem function: +$LogCommandLifeCycleEvent = $false ``` -To count the functions in the current session, type: - -```powershell -(Get-ChildItem function:).count -``` +The events that you enable are effective only for the current PowerShell +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -#### \$MaximumHistoryCount +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount - -Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". - -To find the current number of variables on the system, type: +### \$OFS -```powershell -(Get-Variable).count -``` - -#### \$OFS +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. +**Valid values**: Any string. -Valid values: Any string. -Default: Space +**Default**: Space -By default, the \$OFS variable does not exist and the output file separator is +By default, the `$OFS` variable doesn't exist and the output file separator is a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. +the value of `$OFS` in your session, by typing `$OFS=""`. -For example: +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 - -2 +#### Examples -3 - -4 -``` - -##### EXAMPLES - -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: UTF8Encoding object (System.Text.UTF8Encoding) +**Default**: UTF8Encoding object (System.Text.UTF8Encoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. - -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +session configuration that's located on the remote computer. -The default value: +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1128,226 +1016,274 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your PowerShell profile. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). - -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` + +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the SilentlyContinue value. +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +This example uses the **WarningAction** parameter to stop when a warning is +generated. -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` + +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[?] Help (default is "Y"): +``` -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` + +```Output WARNING: This action can delete data. Confirm @@ -1356,148 +1292,200 @@ Continue with this operation? [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference + +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +The valid values are as follows: -Valid values: +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +#### Examples -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt +``` -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +```powershell +Get-ChildItem -Path .\test.txt ``` -##### EXAMPLES +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +```Output + Directory: C:\Test -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. + +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt +``` -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Get-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword +``` + +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` + +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. + +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) +[about_Variables](about_Variables.md) diff --git a/reference/7/Microsoft.PowerShell.Core/About/about_Preference_Variables.md b/reference/7/Microsoft.PowerShell.Core/About/about_Preference_Variables.md index 4feac8b00f86..3a8929731f6c 100644 --- a/reference/7/Microsoft.PowerShell.Core/About/about_Preference_Variables.md +++ b/reference/7/Microsoft.PowerShell.Core/About/about_Preference_Variables.md @@ -1,19 +1,21 @@ --- -ms.date: 12/21/2017 +ms.date: 09/13/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet title: about_Preference_Variables --- + # About Preference Variables -## SHORT DESCRIPTION -Variables that customize the behavior of PowerShell +## Short description + +Variables that customize the behavior of PowerShell. -## LONG DESCRIPTION +## Long description PowerShell includes a set of variables that enable you to customize its -behavior. These "preference variables" work like the options in GUI-based +behavior. These preference variables work like the options in GUI-based systems. The preference variables affect the PowerShell operating environment and all @@ -22,1088 +24,962 @@ that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. -Variable = Default Value - -- \$ConfirmPreference = High -- \$DebugPreference = SilentlyContinue -- \$ErrorActionPreference = Continue -- \$ErrorView = NormalView -- \$FormatEnumerationLimit = 4 -- \$InformationPreference = SilentlyContinue -- \$LogCommandHealthEvent = False (not logged) -- \$LogCommandLifecycleEvent = False (not logged) -- \$LogEngineHealthEvent = True (logged) -- \$LogEngineLifecycleEvent = True (logged) -- \$LogProviderLifecycleEvent = True (logged) -- \$LogProviderHealthEvent = True (logged) -- \$MaximumAliasCount = 4096 -- \$MaximumDriveCount = 4096 -- \$MaximumErrorCount = 256 -- \$MaximumFunctionCount = 4096 -- \$MaximumHistoryCount = 4096 -- \$MaximumVariableCount = 4096 -- \$OFS = (Space character (" ")) -- \$OutputEncoding = UTF8Encoding object -- \$ProgressPreference = Continue -- \$PSDefaultParameterValues = (None - empty hash table) -- \$PSEmailServer = (None) -- \$PSModuleAutoLoadingPreference= All -- \$PSSessionApplicationName = WSMAN -- \$PSSessionConfigurationName = - http://schemas.microsoft.com/PowerShell/microsoft.PowerShell -- \$PSSessionOption = (See below) -- \$VerbosePreference = SilentlyContinue -- \$WarningPreference = Continue -- \$WhatIfPreference = 0 - -PowerShell also includes the following environment variables that store user -preferences. For more information about these environment variables, see -[about_Environment_Variables](about_Environment_Variables.md). - -- PSExecutionPolicyPreference -- PSModulePath - -### WORKING WITH PREFERENCE VARIABLES +| Variable | Default Value | +| -------- | ------------- | +| `$ConfirmPreference` | High| +| `$DebugPreference` | SilentlyContinue | +| `$ErrorActionPreference` | Continue | +| `$ErrorView` | NormalView | +| `$FormatEnumerationLimit` | 4 | +| `$InformationPreference` | SilentlyContinue | +| `$LogCommandHealthEvent` | False (not logged) | +| `$LogCommandLifecycleEvent` | False (not logged) | +| `$LogEngineHealthEvent` | True (logged) | +| `$LogEngineLifecycleEvent` | True (logged) | +| `$LogProviderLifecycleEvent` | True (logged) | +| `$LogProviderHealthEvent` | True (logged) | +| `$MaximumHistoryCount` | 4096 | +| `$OFS` | (Space character (`" "`)) | +| `$OutputEncoding` | UTF8Encoding object | +| `$ProgressPreference` | Continue | +| `$PSDefaultParameterValues` | (None - empty hash table) | +| `$PSEmailServer` | (None) | +| `$PSModuleAutoLoadingPreference` | All | +| `$PSSessionApplicationName` | WSMAN | +| `$PSSessionConfigurationName` | `http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` | +| `$PSSessionOption` | See [$PSSessionOption](#pssessionoption)| +| `$VerbosePreference` | SilentlyContinue | +| `$WarningPreference` | Continue | +| `$WhatIfPreference` | 0 | + +PowerShell includes the following environment variables that store user +preferences. For more information about these environment variables, see [about_Environment_Variables](about_Environment_Variables.md). + +- `env:PSExecutionPolicyPreference` +- `$env:PSModulePath` + +## Working with preference variables This document describes each of the preference variables. -To display the current value of a specific preference variable, type the name -of the variable. In response, PowerShell provides the value. For example, the -following command displays the value of the \$ConfirmPreference variable. +To display the current value of a specific preference variable, type the +variable's name. For example, the following command displays the +`$ConfirmPreference` variable's value. ```powershell -PS> $ConfirmPreference + $ConfirmPreference +``` + +```Output High ``` -To change the value of a variable, use an assignment statement. For example, -the following statement assigns the value "Medium" to the \$ConfirmPreference -variable. +To change a variable's value, use an assignment statement. For example, the +following statement changes the `$ConfirmPreference` parameter's value to +**Medium**. ```powershell -PS> $ConfirmPreference = "Medium" +$ConfirmPreference = "Medium" ``` -Like all variables, the values that you set are specific to the current -PowerShell session. To make them effective in all PowerShell session, -add them to your PowerShell profile. For more information, see about_Profiles. +The values that you set are specific to the current PowerShell session. To make +variables effective in all PowerShell sessions, add them to your PowerShell +profile. For more information, see [about_Profiles](about_Profiles.md). -### WORKING REMOTELY +## Working remotely -When you run commands on a remote computer, the remote commands are subject -only to the preferences set in the PowerShell client on the remote computer. -For example, when you run a remote command, the value of the \$DebugPreference -variable on remote computer determines how PowerShell responds to -debugging messages. +When you run commands on a remote computer, the remote commands are only +subject to the preferences set in the remote computer's PowerShell client. For +example, when you run a remote command, the value of the remote computer's +`$DebugPreference` variable determines how PowerShell responds to debugging +messages. -For more information about remote commands, see -[about_remote](about_Remote.md). +For more information about remote commands, see [about_Remote](about_Remote.md). -#### \$ConfirmPreference +### \$ConfirmPreference -Determines whether PowerShell automatically prompts you for confirmation -before running a cmdlet or function. +Determines whether PowerShell automatically prompts you for confirmation before +running a cmdlet or function. -When the value of the \$ConfirmPreference variable (High, Medium, Low) is less -than or equal to the risk assigned to the cmdlet or function (High, Medium, -Low), PowerShell automatically prompts you for confirmation before running the -cmdlet or function. +The `$ConfirmPreference` variable's valid values are **High**, **Medium**, or +**Low**. Cmdlets and functions are assigned a risk of **High**, **Medium**, or +**Low**. When the value of the `$ConfirmPreference` variable is less than or +equal to the risk assigned to a cmdlet or function, PowerShell automatically +prompts you for confirmation before running the cmdlet or function. -If the value of the \$ConfirmPreference variable is None, PowerShell never +If the value of the `$ConfirmPreference` variable is **None**, PowerShell never automatically prompts you before running a cmdlet or function. -To change the confirming behavior for all cmdlets and functions in the -session, change the value of the \$ConfirmPreference variable. +To change the confirming behavior for all cmdlets and functions in the session, +change `$ConfirmPreference` variable's value. -To override the \$ConfirmPreference for a single command, use the Confirm -parameter of the cmdlet or function. To request confirmation, use -Confirm. To -suppress confirmation, use -Confirm:\$false +To override the `$ConfirmPreference` for a single command, use a cmdlet's or +function's **Confirm** parameter. To request confirmation, use `-Confirm`. To +suppress confirmation, use `-Confirm:$false`. -Valid values of \$ConfirmPreference: +Valid values of `$ConfirmPreference`: -- None: PowerShell does not prompt automatically. To request confirmation - of a particular command, use the Confirm parameter of the cmdlet or +- **None**: PowerShell doesn't prompt automatically. To request confirmation of + a particular command, use the **Confirm** parameter of the cmdlet or function. -- Low: PowerShell prompts for confirmation before running cmdlets or +- **Low**: PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. -- Medium: PowerShell prompts for confirmation before running cmdlets or +- **Medium**: PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. -- High: PowerShell prompts for confirmation before running cmdlets or +- **High**: PowerShell prompts for confirmation before running cmdlets or functions with a high risk. -##### DETAILED EXPLANATION - -When the actions of a cmdlet or function significantly affect the system, such -as those that delete data or use a significant amount of system resources, -PowerShell can automatically prompt you for confirmation before performing the -action. +#### Detailed explanation -For example, +PowerShell can automatically prompt you for confirmation before doing an +action. For example, when cmdlet or function significantly affects the system +to delete data or use a significant amount of system resources. ```powershell -PS> remove-item file.txt +Remove-Item -Path C:\file.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". -[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"): ``` -The estimate of the risk is an attribute of the cmdlet or function known as -its "ConfirmImpact". Users cannot change it. +The estimate of the risk is an attribute of the cmdlet or function known as its +**ConfirmImpact**. Users can't change it. -Cmdlets and functions that might pose a risk to the system have a Confirm +Cmdlets and functions that might pose a risk to the system have a **Confirm** parameter that you can use to request or suppress confirmation for a single command. -Because most cmdlets and functions use the default risk value (ConfirmImpact) -of Medium, and the default value of \$ConfirmPreference is High, automatic -confirmation rarely occurs. However, you can activate automatic confirmation -by changing the value of \$ConfirmPreference to Medium or Low. +Because most cmdlets and functions use the default risk value, +**ConfirmImpact**, of **Medium**, and the default value of `$ConfirmPreference` +is **High**, automatic confirmation rarely occurs. However, you can activate +automatic confirmation by changing the value of `$ConfirmPreference` to +**Medium** or **Low**. -##### EXAMPLES +#### Examples -This example shows the effect of the default value of \$ConfirmPreference. The -High value only confirms high-risk cmdlets and functions. Since most cmdlets -and functions are medium risk, they are not automatically confirmed. +This example shows the effect of the `$ConfirmPreference` variable's default +value, **High**. The **High** value only confirms high-risk cmdlets and +functions. Since most cmdlets and functions are medium risk, they aren't +automatically confirmed and `Remove-Item` deletes the file. Adding `-Confirm` +to the command prompts the user for confirmation. ```powershell -PS> $confirmpreference #Get the current value of the variable +$ConfirmPreference +``` + +```Output High +``` -PS> remove-item temp1.txt #Delete a file -PS> #Deleted without confirmation +```powershell +Remove-Item -Path C:\temp1.txt +``` -PS> remove-item temp2.txt -confirm #Use to request confirmation +Use `-Confirm` to request confirmation. + +```powershell +Remove-Item -Path C:\temp2.txt -Confirm +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". -[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"): ``` The following example shows the effect of changing the value of -\$ConfirmPreference to Medium. Because most cmdlets and function are -medium-risk, they are automatically confirmed. To suppress the confirmation -prompt for a single command, use the Confirm parameter with a value of \$false +`$ConfirmPreference` to **Medium**. Because most cmdlets and function are +medium risk, they're automatically confirmed. To suppress the confirmation +prompt for a single command, use the **Confirm** parameter with a value of +`$false`. ```powershell -PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference -PS> remove-item temp2.txt #Deleting a file triggers confirmation +$ConfirmPreference = "Medium" +Remove-Item -Path C:\temp2.txt +``` +```Output Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". -[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"): +``` -PS> remove-item temp3.txt -confirm:$false #Use to suppress confirmation -PS> +```powershell +Remove-Item -Path C:\temp3.txt -Confirm:$false ``` -#### \$DebugPreference +### \$DebugPreference -Determines how PowerShell responds to debugging messages generated by a -script, cmdlet or provider, or by a Write-Debug command at the command -line. +Determines how PowerShell responds to debugging messages generated by a script, +cmdlet or provider, or by a `Write-Debug` command at the command line. -Some cmdlets display debugging messages, which are typically very technical -messages designed for programmers and technical support professionals. By -default, debugging messages are not displayed, but you can display -debugging messages by changing the value of \$DebugPreference. +Some cmdlets display debugging messages, which are typically technical messages +designed for programmers and technical support professionals. By default, +debugging messages aren't displayed, but you can display debugging messages by +changing the value of `$DebugPreference`. -You can also use the Debug common parameter of a cmdlet to display or hide -the debugging messages for a specific command. For more information, type: -`get-help about_commonparameters`. +You can use the **Debug** common parameter of a cmdlet to display or hide the +debugging messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the debug message and stops executing. Writes an error to +- **Stop**: Displays the debug message and stops executing. Writes an error to the console. - -- Inquire: Displays the debug message and asks you whether you want to - continue. Note that adding the Debug common parameter to a command--when - the command is configured to generate a debugging message--changes the - value of the \$DebugPreference variable to Inquire. - -- Continue: Displays the debug message and continues with execution. - -- SilentlyContinue: No effect. The debug message is not (Default) displayed +- **Inquire**: Displays the debug message and asks you whether you want to + continue. Adding the **Debug** common parameter to a command, when the + command is configured to generate a debugging message, changes the value of + the `$DebugPreference` variable to **Inquire**. +- **Continue**: Displays the debug message and continues with execution. +- **SilentlyContinue**: (Default) No effect. The debug message isn't displayed and execution continues without interruption. -##### EXAMPLES +#### Examples The following examples show the effect of changing the values of -\$DebugPreference when a Write-Debug command is entered at the command line. -The change affects all debugging messages, including those generated by -cmdlets and scripts. The examples also show the use of the Debug common -parameter, which displays or hides the debugging messages related to a -single command. +`$DebugPreference` when a `Write-Debug` command is entered at the command line. +The change affects all debugging messages, including messages generated by +cmdlets and scripts. The examples show the **Debug** parameter, which displays +or hides the debugging messages related to a single command. -This example shows the effect of the default value, "SilentlyContinue." The -debug message is not displayed and processing continues. The final command -uses the Debug parameter to override the preference for a single command. +This example shows the effect of the `$DebugPreference` variable's default +value, **SilentlyContinue**. By default, the `Write-Debug` cmdlet's debug +message isn't displayed and processing continues. When the **Debug** parameter +is used, it overrides the preference for a single command. The debug message is displayed. ```powershell -PS> $debugpreference # Get the current value of $DebugPreference +$DebugPreference +``` + +```Output SilentlyContinue +``` -PS> write-debug "Hello, World" -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" +``` -PS> # Use the Debug parameter to display message and request confirmation -PS> write-debug "Hello, World" -Debug +```powershell +Write-Debug -Message "Hello, World" -Debug +``` + +```Output DEBUG: Hello, World -Confirm -Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): ``` -This example shows the effect of the "Continue" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` with the **Continue** +value. The debug message is displayed and the command continues to process. ```powershell -PS> $debugpreference = "Continue" # Change the value to "Continue" +$DebugPreference = "Continue" +Write-Debug -Message "Hello, World" +``` + +```Output +DEBUG: Hello, World +``` -PS> write-debug "Hello, World" -DEBUG: Hello, World # Display message and continue processing. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed. -PS> # Use the Debug parameter with false. -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Stop" value. The final command uses -the Debug parameter with a value of \$false to suppress the message for a -single command. +This example shows the effect of `$DebugPreference` being set to the **Stop** +value. The debug message is displayed and the command is stopped. ```powershell -PS> $debugpreference = "Stop" #Change the value to "Stop" -PS> Write-Debug "Hello, World" +$DebugPreference = "Stop" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World -Write-Debug : Command execution stopped because the shell variable "Debug -Preference" is set to Stop. -At line:1 char:12 -+ Write-Debug <<<< "Hello, World" +Write-Debug : The running command stopped because the preference variable + "DebugPreference" or common parameter is set to Stop: Hello, World +At line:1 char:1 ++ Write-Debug -Message "Hello, World" +``` + +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing isn't stopped. -PS> # Use the Debug parameter with $false -PS> Write-Debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing is not stopped. +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -This example shows the effect of the "Inquire" value. The final command -uses the Debug parameter with a value of \$false to suppress the message for -a single command. +This example shows the effect of `$DebugPreference` being set to the +**Inquire** value. The debug message is displayed and the user is prompted for +confirmation. ```powershell -PS> $debugpreference = "Inquire" -PS> write-debug "Hello, World" +$DebugPreference = "Inquire" +Write-Debug -Message "Hello, World" +``` + +```Output DEBUG: Hello, World Confirm Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): +``` -PS> # Use the Debug parameter with $false -PS> write-debug "Hello, World" -Debug:$false -PS> # The debug message is not displayed and processing continues. +This example uses the **Debug** parameter with a value of `$false` to suppress +the message for a single command. The debug message isn't displayed and +processing continues. + +```powershell +Write-Debug -Message "Hello, World" -Debug:$false ``` -#### \$ErrorActionPreference +### \$ErrorActionPreference -Determines how PowerShell responds to a non-terminating error (an error that -does not stop the cmdlet processing) at the command line or in a script, -cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. +Determines how PowerShell responds to a non-terminating error, an error that +doesn't stop the cmdlet processing. For example, at the command line or in a +script, cmdlet, or provider, such as the errors generated by the `Write-Error` +cmdlet. -You can also use the ErrorAction common parameter of a cmdlet to override the +You can use a cmdlet's **ErrorAction** common parameter to override the preference for a specific command. -Valid values: +The valid values are as follows: -- Stop: Displays the error message and stops executing. -- Inquire: Displays the error message and asks you whether you want to +- **Stop**: Displays the error message and stops executing. +- **Inquire**: Displays the error message and asks you whether you want to continue. -- Continue: Displays the error message and continues (Default) executing. -- Suspend: Automatically suspends a workflow job to allow for further - investigation. After investigation, the workflow can be resumed. -- SilentlyContinue: No effect. The error message is not displayed and +- **Continue**: (Default) Displays the error message and continues executing. +- **SilentlyContinue**: No effect. The error message isn't displayed and execution continues without interruption. +- **Ignore**: Suppresses the error message and continues to execute the + command. The **Ignore** value is intended for per-command use, not for use as + saved preference. **Ignore** isn't a valid value for the + `$ErrorActionPreference` variable. -NOTE: The Ignore value of the ErrorAction common parameter is not a valid -value of the \$ErrorActionPreference variable. The Ignore value is intended -for per-command use, not for use as saved preference. - -Neither \$ErrorActionPreference nor the ErrorAction common parameter affect -how PowerShell responds to terminating errors (those that stop cmdlet -processing). +The `$ErrorActionPreference` and **ErrorAction** parameter don't affect how +PowerShell responds to terminating errors that stop cmdlet processing. For more +information about the **ErrorAction** common parameter, see [about_CommonParameters](about_CommonParameters.md). -For more information about the ErrorAction common parameter, see -[about_CommonParameters](about_CommonParameters.md). +#### Examples -##### EXAMPLES +These examples show the effect of the different values of the +`$ErrorActionPreference` variable. The **ErrorAction** parameter is used to +override the `$ErrorActionPreference` value. -These examples show the effect of the different values of -\$ErrorActionPreference and the use of the ErrorAction common parameter to -override the preference for a single command. The ErrorAction parameter has -the same valid values as the \$ErrorActionPreference variable. +This example shows the `$ErrorActionPreference` default value, **Continue**. A +non-terminating error is generated. The message is displayed and processing +continues. -This example shows the effect of the Continue value, which is the default. - -```powershell +``` +PS> $ErrorActionPreference = "Continue" PS> # Display the value of the preference. -PS> $erroractionpreference +PS> $ErrorActionPreference Continue - PS> # Generate a non-terminating error. -PS> write-error "Hello, World" - +PS> Write-Error -Message "Hello, World" +Write-Error -Message "Hello, World" : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error],WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> # The error message is displayed and execution continues. -PS> write-error "Hello, World" : Hello, World - PS> # Use the ErrorAction parameter with a value of "SilentlyContinue". -PS> write-error "Hello, World" -ErrorAction:SilentlyContinue -PS> # The error message is not displayed and execution continues. +PS> Write-Error -Message "Hello, World" -ErrorAction:SilentlyContinue +PS> # The error message isn't displayed and execution continues. ``` -This example shows the effect of the SilentlyContinue value. +This example shows the `$ErrorActionPreference` set to **SilentlyContinue**. +The error message is suppressed. -```powershell -PS> # Change the value of the preference. +``` +PS> # Display the value of the preference PS> $ErrorActionPreference = "SilentlyContinue" - -PS> # Generate an error message. -PS> Write-Error "Hello, World" -PS> # Error message is suppressed. - -PS> # Use the ErrorAction parameter with a value of "Continue". -PS> Write-Error "Hello, World" -erroraction:continue - -PS> # The error message is displayed and execution continues. -Write-Error "Hello, World" -erroraction:continue : Hello, World +PS> # Generate an error message +PS> Write-Error -Message "Hello, World" +PS> # Error message is suppressed +PS> # Use the ErrorAction parameter with a value of "Continue" +PS> Write-Error -Message "Hello, World" -ErrorAction:Continue +Write-Error -Message "Hello, World" -ErrorAction:Continue : Hello, World ++ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException ++ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException ``` -This example shows the effect of a real error. In this case, the command gets -a non-existent file, nofile.txt. The example also uses the ErrorAction common -parameter to override the preference. - -```powershell -PS> $erroractionpreference -SilentlyContinue # Display the value of the preference. - -PS> Get-ChildItem -path nofile.txt -PS> # Error message is suppressed. +This example shows the effect of a real error. In this case, the command gets a +non-existent file, `nofile.txt`. +``` +PS> # Display the value of the preference. +PS> $ErrorActionPreference +SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt +PS> # Error message is suppressed. PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" - -PS> Get-ChildItem -path nofile.txt +PS> Get-ChildItem -Path C:\nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Use the ErrorAction parameter -PS> Get-ChildItem -path nofile.txt -erroraction SilentlyContinue +PS> Get-ChildItem -Path C:\nofile.txt -ErrorAction SilentlyContinue PS> # Error message is suppressed. - PS> # Change the value to Inquire. PS> $ErrorActionPreference = "Inquire" -PS> Get-ChildItem -path nofile.txt - +PS> Get-ChildItem -Path C:\nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y - +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): Y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:4 -+ Get-ChildItem <<<< nofile.txt - +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand PS> # Change the value to Continue. PS> $ErrorActionPreference = "Continue" -PS> Get-Childitem nofile.txt -erroraction "Inquire" PS> # Use the ErrorAction parameter to override the preference value. - +PS> Get-Childitem C:\nofile.txt -ErrorAction "Inquire" Confirm Cannot find path 'C:\nofile.txt' because it does not exist. -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): Y +Get-Childitem : Cannot find path 'C:\nofile.txt' because it does not exist. +At line:1 char:1 ++ Get-Childitem C:\nofile.txt -ErrorAction "Inquire" ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ++ CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException ++ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands. + GetChildItemCommand ``` -#### \$ErrorView +### \$ErrorView Determines the display format of error messages in PowerShell. -Valid values: +The valid values are as follows: -- NormalView: A detailed view designed for most users. (default) Consists - of a description of the error, the name of the object involved in the - error, and arrows (<<<<) that point to the words in the command that - caused the error. -- CategoryView: A succinct, structured view designed for production - environments. The format is: +- **NormalView**: (Default) A detailed view designed for most users. Consists + of a description of the error, and the name of the object involved in the + error. +- **CategoryView**: A succinct, structured view designed for production + environments. The format is as follows: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} -For more information about the fields in CategoryView, see -"ErrorCategoryInfo class" in the PowerShell SDK. - -##### EXAMPLES +For more information about the fields in **CategoryView**, see [ErrorCategoryInfo](/dotnet/api/system.management.automation.errorcategoryinfo) +class. -These example show the effect of the ErrorView values. +#### Examples -This example shows how an error appears when the value of \$ErrorView is -NormalView. In this case, the Get-ChildItem command is used to find a -non-existent file. +This example shows how an error appears when the value of `$ErrorView` is the +default, **NormalView**. `Get-ChildItem` is used to find a non-existent file. ```powershell -PS> $ErrorView # Verify the value. -NormalView +Get-ChildItem -Path C:\nofile.txt +``` -PS> Get-ChildItem nofile.txt # Find a non-existent file. +```Output Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< nofile.txt +At line:1 char:1 ++ Get-ChildItem -Path C:\nofile.txt ``` -This example shows how the same error appears when the value of -\$ErrorView is CategoryView. +This example shows how the same error appears when the value of `$ErrorView` is +changed to **CategoryView**. ```powershell -PS> $ErrorView = "CategoryView" # Change the value to -CategoryView +$ErrorView = "CategoryView" +Get-ChildItem -Path C:\nofile.txt +``` -PS> get-childitem nofile.txt -ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundExcep -tion +```Output +ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException ``` -This example demonstrates that the value of ErrorView only affects the error -display; it does not change the structure of the error object that is stored -in the \$error automatic variable. For information about the \$error automatic +This example demonstrates that the value of `$ErrorView` only affects the error +display. It doesn't change the structure of the error object that is stored in +the `$Error` automatic variable. For information about the `$Error` automatic variable, see [about_automatic_variables](about_Automatic_Variables.md). -This command takes the ErrorRecord object associated with the most recent -error in the error array (element 0) and formats all of the properties of the -error object in a list. +The following command takes the **ErrorRecord** object associated with the most +recent error in the error array, **element 0**, and formats all the error +object's properties in a list. ```powershell -PS> $error[0] | Format-List -Property * -force - -Exception : System.Management.Automation.ItemNotFoundException: Cannot -find path 'C:\nofile.txt' because it does not exist. -at System.Management.Automation.SessionStateInternal.GetChildItems(String -path, Boolean recurse, CmdletProviderContext context) -at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(Stri -ng path,Boolean recurse, CmdletProviderContext context) -at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() +$Error[0] | Format-List -Property * -Force +``` + +```Output +PSMessageDetails : +Exception : System.Management.Automation.ItemNotFoundException: + Cannot find path 'C:\nofile.txt' because it does + not exist. + at System.Management.Automation.SessionStateInternal. + GetChildItems(String path, Boolean recurse, UInt32 + depth, CmdletProviderContext context) + at System.Management.Automation.ChildItemCmdlet + ProviderIntrinsics.Get(String path, Boolean + recurse, UInt32 depth, CmdletProviderContext context) + at Microsoft.PowerShell.Commands.GetChildItemCommand. + ProcessRecord() TargetObject : C:\nofile.txt -CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildI -tem],ItemNotFoundException -FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChil -dItemCommand +CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], + ItemNotFoundException +FullyQualifiedErrorId : PathNotFound, + Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo +ScriptStackTrace : at , : line 1 +PipelineIterationInfo : {0, 1} ``` -#### \$FormatEnumerationLimit +### \$FormatEnumerationLimit -Determines how many enumerated items are included in a display. This -variable does not affect the underlying objects; just the display. When the -value of \$FormatEnumerationLimit is less than the number of enumerated -items, PowerShell adds an ellipsis (...) to indicate items not shown. +Determines how many enumerated items are included in a display. This variable +doesn't affect the underlying objects, only the display. When the value of +`$FormatEnumerationLimit` is fewer than the number of enumerated items, +PowerShell adds an ellipsis (`...`) to indicate items not shown. -Valid values: Integers (Int32) +**Valid values**: Integers (`Int32`) -Default value: 4 +**Default value**: 4 -##### EXAMPLES +#### Examples -This example shows how to use the \$FormatEnumerationLimit variable to -improve the display of enumerated items. +This example shows how to use the `$FormatEnumerationLimit` variable to improve +the display of enumerated items. -The command in this example generates a table that lists all of the services -running on the computer in two groups; one for running services and one for -stopped services. It uses a Get-Service command to get all of the services, -and then send the results through the pipeline to the Group-Object cmdlet, +The command in this example generates a table that lists all the services +running on the computer in two groups: one for **running** services and one for +**stopped** services. It uses a `Get-Service` command to get all the services, +and then sends the results through the pipeline to the `Group-Object` cmdlet, which groups the results by the service status. -The resulting display is a table that lists the status in the Name column and -the processes with that status in the Group column. (To change the column -labels, use a hash table. For more information, see the examples in "get-help -format-table -examples".) - -There are a maximum of 4 services listed in the Group column for each status. -To increase the number of items listed, increase the value of -\$FormatEnumerationLimit to 1000. - -In the resulting display, the list in the Group column is now limited by the -line length. In the final command in the example, use the Wrap parameter of -Format-Table to display all of the processes in each Status group. - -```powershell -PS> $formatenumerationlimit # Find the current value -4 - -PS> # List all services grouped by status -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} -PS> # The list is truncated after 4 items. - -PS> # Increase the limit to 1000. -PS> $formatenumerationlimit = 1000 -PS> get-service | Group-Object -Property status - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... - -PS> # Add the Wrap parameter. -PS> get-service | Group-Object -Property status | Format-Table -wrap - -Count Name Group ------ ---- ----- -60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, - Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, - Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, - HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, - lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, - NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, - RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, - SharedAccess, ShellHWDetection, SMT PSVC, Spooler, - srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, - TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, - wuauserv, WZCSVC, zzInterix} - -41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, - ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, - CronService, dmadmin, FastUserSwitchingCompatibility, - HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, - MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, - NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, - SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, - WmdmPmSN, Wmi, WmiApSrv, xmlprov} -``` - -#### \$InformationPreference - -The \$InformationPreference variable lets you set information stream -preferences (specifically, informational messages that you have added to -commands or scripts by adding the Write-Information cmdlet, and want displayed -to users) for a PowerShell session. The value of the -InformationAction -parameter, if used, overrides the current value of the \$InformationPreference -variable. - -Valid values: - -- Stop: Stops a command or script at an occurrence of the Write-Information - command. -- Inquire: Displays the informational message that you specify in a - Write-Information command, then asks whether you want to continue. -- Continue: Displays the informational message, and continues running. -- Suspend: Automatically suspends a workflow job after a Write-Information - command is carried out, to allow users to see the messages before - continuing. The workflow can be resumed at the user's discretion. -- SilentlyContinue: No effect. The informational messages are not (Default) - displayed, and the script continues without interruption. - - -#### \$Log*Event - -The Log*Event preference variables determine which types of events are written -to the PowerShell event log in Event Viewer. By default, only engine and -provider events are logged, but you can use the Log*Event preference variables -to customize your log, such as logging events about commands. - -The Log*Event preference variables are as follows: - -- \$LogCommandHealthEvent: Logs errors and exceptions in command - initialization and processing. Default = \$false (not logged). - -- \$LogCommandLifecycleEvent: Logs the starting and stopping of commands and - command pipelines and security exceptions in command discovery. Default = - \$false (not logged). - -- \$LogEngineHealthEvent: Logs errors and failures of sessions. Default = - \$true (logged). - -- \$LogEngineLifecycleEvent: Logs the opening and closing of sessions. - Default = \$true (logged). - -- \$LogProviderHealthEvent: Logs provider errors, such as read and write - errors, lookup errors, and invocation errors. Default = \$true (logged). - -- \$LogProviderLifecycleEvent: Logs adding and removing of PowerShell - providers. Default = \$true (logged). (For information about PowerShell - providers, type: "get-help about_provider". - -To enable a Log*Event, type the variable with a value of \$true, for example: - -```powershell -$LogCommandLifeCycleEvent -``` +The result is a table that lists the status in the **Name** column, and the +processes in the **Group** column. To change the column labels, use a hash +table, see [about_Hash_Tables](about_Hash_Tables.md). For more information, see +the examples in [Format-Table](../../Microsoft.PowerShell.Utility/Format-Table.md). -- or - +Find the current value of `$FormatEnumerationLimit`. ```powershell -$LogCommandLifeCycleEvent = $true +$FormatEnumerationLimit ``` -To disable an event type, type the variable with a value of \$false, for -example: - -```powershell -$LogCommandLifeCycleEvent = $false +```Output +4 ``` -The events that you enable are effective only for the current PowerShell -console. To apply the configuration to all consoles, save the variable -settings in your PowerShell profile. - -#### \$MaximumAliasCount - -Determines how many aliases are permitted in a PowerShell session. The default -value, 4096, should be sufficient for most uses, but you can adjust it to meet -your needs. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To count the aliases on your system, type: +List all services grouped by **Status**. There are a maximum of four services +listed in the **Group** column for each status because +`$FormatEnumerationLimit` has a value of **4**. ```powershell -(Get-Alias).count +Get-Service | Group-Object -Property Status ``` -#### \$MaximumDriveCount - -Determines how many PowerShell drives are permitted in a given session. This -includes file system drives and data stores that are exposed by PowerShell -providers and appear as drives, such as the Alias: and HKLM: drives. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To count the aliases on your system, type: - -```powershell -(Get-PSDrive).count +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} ``` -#### \$MaximumErrorCount - -Determines how many errors are saved in the error history for the session. - -Valid values: 256 - 32768 (Int32) - -Default: 256 - -Objects that represent each retained error are stored in the \$Error automatic -variable. This variable contains an array of error record objects, one for -each error. The most recent error is the first object in the array -(\$Error[0]). - -To count the errors on your system, use the Count property of the \$Error -array. Type: +To increase the number of items listed, increase the value of +`$FormatEnumerationLimit` to **1000**. Use `Get-Service` and `Group-Object` to +display the services. ```powershell -$Error.count +$FormatEnumerationLimit = 1000 +Get-Service | Group-Object -Property Status ``` -To display a specific error, use array notation to display the error. For -example, to see the most recent error, type: - -```powershell -$Error[0] +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... ``` -To display the oldest retained error, type: +Use `Format-Table` with the **Wrap** parameter to display the list of services. ```powershell -$Error[($Error.Count -1] +Get-Service | Group-Object -Property Status | Format-Table -Wrap ``` -To display the properties of the ErrorRecord object, type: - -```powershell -$Error[0] | Format-List -Property * -force +```Output +Count Name Group +----- ---- ----- +60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, + Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, + Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, + HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, + lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, + NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, + RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, + SharedAccess, ShellHWDetection, SMT PSVC, Spooler, + srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, + TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, + wuauserv, WZCSVC, zzInterix} + +41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, + ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, + CronService, dmadmin, FastUserSwitchingCompatibility, + HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, + MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, + NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, + SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, + WmdmPmSN, Wmi, WmiApSrv, xmlprov} ``` -In this command, the Force parameter overrides the special formatting of -ErrorRecord objects and reverts to the conventional format. - -To delete all errors from the error history, use the Clear method of the error -array. +### \$InformationPreference -```powershell -PS> $Error.count -17 -PS> $Error.clear() -PS> -PS> $Error.count -0 -``` +The `$InformationPreference` variable lets you set information stream +preferences that you want displayed to users. Specifically, informational +messages that you added to commands or scripts by adding the [Write-Information](../../Microsoft.PowerShell.Utility/Write-Information.md) +cmdlet. If the **InformationAction** parameter is used, its value overrides the +value of the `$InformationPreference` variable. `Write-Information` was +introduced in PowerShell 5.0. -To find all properties and methods of an error array, use the Get-Member -cmdlet with its InputObject parameter. When you pipe a collection of objects -to Get-Member, Get-Member displays the properties and methods of the objects -in the collection. When you use the InputObject parameter of Get-Member, -Get-Member displays the properties and methods of the collection. +The valid values are as follows: -#### \$MaximumFunctionCount - -Determines how many functions are permitted in a given session. - -Valid values: 1024 - 32768 (Int32) - -Default: 4096 - -To see the functions in your session, use the PowerShell Function: drive that -is exposed by the PowerShell Function provider. (For more information about -the Function provider, type "get-help function"). +- **Stop**: Stops a command or script at an occurrence of the + `Write-Information` command. +- **Inquire**: Displays the informational message that you specify in a + `Write-Information` command, then asks whether you want to continue. +- **Continue**: Displays the informational message, and continues running. +- **SilentlyContinue**: (Default) No effect. The informational messages aren't + displayed, and the script continues without interruption. -To list the functions in the current session, type: +### \$Log*Event + +The **Log*Event** preference variables determine which types of events are +written to the PowerShell event log in Event Viewer. By default, only engine +and provider events are logged. But, you can use the **Log*Event** preference +variables to customize your log, such as logging events about commands. + +The **Log*Event** preference variables are as follows: + +- `$LogCommandHealthEvent`: Logs errors and exceptions in command + initialization and processing. The default is `$false` (not logged). +- `$LogCommandLifecycleEvent`: Logs the starting and stopping of commands and + command pipelines and security exceptions in command discovery. The default + is `$false` (not logged). +- `$LogEngineHealthEvent`: Logs errors and failures of sessions. The default is + `$true` (logged). +- `$LogEngineLifecycleEvent`: Logs the opening and closing of sessions. The + default is `$true` (logged). +- `$LogProviderHealthEvent`: Logs provider errors, such as read and write + errors, lookup errors, and invocation errors. The default is `$true` + (logged). +- `$LogProviderLifecycleEvent`: Logs adding and removing of PowerShell + providers. The default is `$true` (logged). For information about PowerShell + providers, see [about_Providers](about_Providers.md). + +To enable a **Log*Event**, type the variable with a value of `$true`, for +example: ```powershell -Get-ChildItem function: +$LogCommandLifeCycleEvent = $true ``` -To count the functions in the current session, type: +To disable an event type, type the variable with a value of `$false`, for +example: ```powershell -(Get-ChildItem function:).count +$LogCommandLifeCycleEvent = $false ``` -#### \$MaximumHistoryCount +The events that you enable are effective only for the current PowerShell +console. To apply the configuration to all consoles, save the variable settings +in your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). + +### \$MaximumHistoryCount -Determines how many commands are saved in the command history for the -current session. +Determines how many commands are saved in the command history for the current +session. -Valid values: 1 - 32768 (Int32) +**Valid values**: 1 - 32768 (`Int32`) -Default: 4096 +**Default**: 4096 -To determine the number of commands current saved in the command -history, type: +To determine the number of commands current saved in the command history, type: ```powershell -(Get-History).count +(Get-History).Count ``` -To see the command saved in your session history, use the Get-History +To see the commands saved in your session history, use the `Get-History` cmdlet. For more information, see [about_History](about_History.md). -#### \$MaximumVariableCount - -Determines how many variables are permitted in a given session, including -automatic variables, preference variables, and the variables that you create -in commands and scripts. - -Valid values: 1024 - 32768 (Int32) +### \$OFS -Default: 4096 +The Output Field Separator (OFS) specifies the character that separates the +elements of an array that is converted to a string. -To see the variables in your session, use the Get-Variable cmdlet and the -features of the PowerShell Variable: drive and the PowerShell Variable -provider. For information about the Variable provider, type "get-help -variable". - -To find the current number of variables on the system, type: - -```powershell -(Get-Variable).count -``` +**Valid values**: Any string. -#### \$OFS +**Default**: Space -Output Field Separator. Specifies the character that separates the elements of -an array when the array is converted to a string. - -Valid values: Any string. -Default: Space - -By default, the \$OFS variable does not exist and the output file separator is +By default, the `$OFS` variable doesn't exist and the output file separator is a space, but you can add this variable and set it to any string. You can change -the value of $OFS in your session, by typing `$OFS=""`. If you are -expecting the default value of " " in your script, module, or configuration -output, be careful that the $OFS default value has not been changed elsewhere -in your code. - -For example: - -```powershell -$a="1","2","3","4" -$a -[string]$a -$OFS="" -[string]$a -$OFS="," -[string]$a -$OFS="--PowerShellRocks--"; -[string]$a -$OFS="`n`n"; -[string]$a -``` - -```output -1 -2 -3 -4 -1 2 3 4 -1234 -1,2,3,4 -1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 -1 - -2 +the value of `$OFS` in your session, by typing `$OFS=""`. -3 +> [!NOTE] +> If you're expecting the default value of a space (`" "`) in your script, +> module, or configuration output, be careful that the `$OFS` default value +> hasn't been changed elsewhere in your code. -4 -``` +#### Examples -##### EXAMPLES - -This example shows that a space is used to separate the values when an array -is converted to a string. In this case, an array of integers is stored in a +This example shows that a space is used to separate the values when an array is +converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. ```powershell -PS> $array = 1,2,3 # Store an array of integers. +$array = 1,2,3,4 +[string]$array +``` -PS> [string]$array # Cast the array to a string. -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -To change the separator, add the \$OFS variable by assigning a value to it. -To work correctly, the variable must be named \$OFS. +To change the separator, add the `$OFS` variable by assigning a value to it. +The variable must be named `$OFS`. ```powershell -PS> $OFS = "+" # Create $OFS and assign a "+" +$OFS = "+" +[string]$array +``` -PS> [string]$array # Repeat the command -1+2+3 # Plus signs separate the elements +```Output +1+2+3+4 ``` -To restore the default behavior, you can assign a space (" ") to the value of -\$OFS or delete the variable. This command deletes the variable and then -verifies that the separator is a space. +To restore the default behavior, you can assign a space (`" "`) to the value of +`$OFS` or delete the variable. The following commands delete the variable and +then verify that the separator is a space. ```powershell -PS> Remove-Variable OFS # Delete $OFS -PS> +Remove-Variable OFS +[string]$array +``` -PS> [string]$array # Repeat the command -1 2 3 # Spaces separate the elements +```Output +1 2 3 4 ``` -#### \$OutputEncoding +### \$OutputEncoding Determines the character encoding method that PowerShell uses when it sends text to other applications. -For example, if an application returns Unicode strings to PowerShell, you -might need to change the value to UnicodeEncoding to send the characters +For example, if an application returns Unicode strings to PowerShell, you might +need to change the value to **UnicodeEncoding** to send the characters correctly. -Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, -SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and -UnicodeEncoding. +The valid values are as follows: Objects derived from an Encoding class, such +as **ASCIIEncoding**, **SBCSCodePageEncoding**, **UTF7Encoding**, +**UTF8Encoding**, **UTF32Encoding**, and **UnicodeEncoding**. -Default: UTF8Encoding object (System.Text.UTF8Encoding) +**Default**: UTF8Encoding object (System.Text.UTF8Encoding) -##### EXAMPLES +#### Examples -This example shows how to make the FINDSTR command in Windows work in +This example shows how to make the Windows **findstr.exe** command work in PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. -The first command finds the value of \$OutputEncoding. Because the value is an -encoding object, display only its EncodingName property. +The first command finds the value of `$OutputEncoding`. Because the value is an +encoding object, display only its **EncodingName** property. ```powershell -PS> $OutputEncoding.EncodingName # Find the current value US-ASCII +$OutputEncoding.EncodingName ``` -In this example, a FINDSTR command is used to search for two Chinese -characters that are present in the Test.txt file. When this FINDSTR command is -run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in -the text file. However, when you run the same FINDSTR command in PowerShell, -the characters are not found because the PowerShell sends them to FINDSTR in -ASCII text, instead of in Unicode text. +In this example, a **findstr.exe** command is used to search for two Chinese +characters that are present in the `Test.txt` file. When this **findstr.exe** +command is run in the Windows Command Prompt (**cmd.exe**), **findstr.exe** +finds the characters in the text file. However, when you run the same +**findstr.exe** command in PowerShell, the characters aren't found because the +PowerShell sends them to **findstr.exe** in ASCII text, instead of in Unicode +text. ```powershell -PS> findstr # Use findstr to search. -PS> # None found. +findstr ``` -To make the command work in PowerShell, set the value of \$OutputEncoding to -the value of the OutputEncoding property of the console, which is based on the -locale selected for Windows. Because OutputEncoding is a static property of -the console, use double-colons (::) in the command. +To make the command work in PowerShell, set the value of `$OutputEncoding` to +the value of the **OutputEncoding** property of the console, that is based on +the locale selected for Windows. Because **OutputEncoding** is a static +property of the console, use double-colons (`::`) in the command. ```powershell -PS> $OutputEncoding = [console]::outputencoding -PS> # Set the value equal to the OutputEncoding property of the console. -PS> $OutputEncoding.EncodingName +$OutputEncoding = [console]::OutputEncoding +$OutputEncoding.EncodingName +``` + +```Output OEM United States ``` -As a result of this change, the FINDSTR command finds the characters. +After the encoding change, the **findstr.exe** command finds the Unicode +characters. ```powershell -PS> findstr +findstr +``` + +```Output test.txt: ``` -#### \$ProgressPreference +### \$ProgressPreference Determines how PowerShell responds to progress updates generated by a script, -cmdlet or provider, such as the progress bars generated by the Write-Progress -cmdlet. The Write-Progress cmdlet creates progress bars that depict the status -of a command. +cmdlet, or provider, such as the progress bars generated by the [Write-Progress](../../Microsoft.PowerShell.Utility/Write-Progress.md) +cmdlet. The `Write-Progress` cmdlet creates progress bars that show a command's +status. -Valid values: +The valid values are as follows: -- Stop: Does not display the progress bar. Instead, it displays an error +- **Stop**: Doesn't display the progress bar. Instead, it displays an error message and stops executing. -- Inquire: Does not display the progress bar. Prompts for permission to - continue. If you reply with Y or A, it displays the progress bar. -- Continue: Displays the progress bar and continues with (Default) +- **Inquire**: Doesn't display the progress bar. Prompts for permission to + continue. If you reply with `Y` or `A`, it displays the progress bar. +- **Continue**: (Default) Displays the progress bar and continues with execution. -- SilentlyContinue: Executes the command, but does not display the progress +- **SilentlyContinue**: Executes the command, but doesn't display the progress bar. -#### \$PSEmailServer +### \$PSEmailServer -Specifies the default e-mail server that is used to send e-mail messages. This -preference variable is used by cmdlets that send e-mail, such as the -Send-MailMessage cmdlet. +Specifies the default e-mail server that is used to send email messages. This +preference variable is used by cmdlets that send email, such as the [Send-MailMessage](../../Microsoft.PowerShell.Utility/Send-MailMessage.md) +cmdlet. -#### \$PSDefaultParameterValues +### \$PSDefaultParameterValues Specifies default values for the parameters of cmdlets and advanced functions. -The value of \$PSDefaultParameterValues is a hash table where the key consists -of the cmdlet name and parameter name separated by a colon (:) and the value -is a custom default value that you specify. +The value of `$PSDefaultParameterValues` is a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (`:`). The value is +a custom default value that you specify. -This variable was introduced in PowerShell 3.0 +`$PSDefaultParameterValues` was introduced in PowerShell 3.0. -For more information about this preference variable, see -[about_Parameters_Default_Values](about_Parameters_Default_Values.md). +For more information about this preference variable, see [about_Parameters_Default_Values](about_Parameters_Default_Values.md). -#### \$PSModuleAutoloadingPreference +### \$PSModuleAutoloadingPreference -Enables and disables automatic importing of modules in the session. "All" is -the default. Regardless of the value of this variable, you can use the -Import-Module cmdlet to import a module. +Enables and disables automatic importing of modules in the session. **All** is +the default. Regardless of the variable's value, you can use [Import-Module](../Import-Module.md) +to import a module. Valid values are: -- All: Modules are imported automatically on first-use. To import a module, - get (Get-Command) or use any command in the module. -- ModuleQualified: Modules are imported automatically only when a user uses +- **All**: Modules are imported automatically on first-use. To import a module, + get or use any command in the module. For example, use `Get-Command`. +- **ModuleQualified**: Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the - user types "MyModule\MyCommand", PowerShell imports the MyModule module. -- None: Automatic importing of modules is disabled in the session. To import - a module, use the Import-Module cmdlet. + user types `MyModule\MyCommand`, PowerShell imports the **MyModule** module. +- **None**: Automatic importing of modules is disabled in the session. To + import a module, use the `Import-Module` cmdlet. -For more information about automatic importing of modules, see -[about_Modules](about_Modules.md). +For more information about automatic importing of modules, see [about_Modules](about_Modules.md). -#### \$PSSessionApplicationName +### \$PSSessionApplicationName -Specifies the default application name for a remote command that uses -WS-Management technology. +Specifies the default application name for a remote command that uses Web +Services for Management (WS-Management) technology. For more information, see +[About Windows Remote Management](/windows/win32/winrm/about-windows-remote-management). -The system default application name is WSMAN, but you can use this preference +The system default application name is `WSMAN`, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the -application name in the following sample URI is WSMAN. +application name in the following sample URI is `WSMAN`. -http://Server01:8080/WSMAN +`http://Server01:8080/WSMAN` -The default application name is used when the remote command does not specify -a connection URI or an application name. +The default application name is used when the remote command doesn't specify a +connection URI or an application name. -The WinRM service uses the application name to select a listener to service -the connection request. The value of this parameter should match the value of -the URLPrefix property of a listener on the remote computer. +The **WinRM** service uses the application name to select a listener to service +the connection request. The parameter's value should match the value of the +**URLPrefix** property of a listener on the remote computer. To override the system default and the value of this variable, and select a -different application name for a particular session, use the ConnectionURI or -ApplicationName parameters of the New-PSSession, Enter-PSSession or -Invoke-Command cmdlets. +different application name for a particular session, use the **ConnectionURI** +or **ApplicationName** parameters of the [New-PSSession](../New-PSSession.md), [Enter-PSSession](../Enter-PSSession.md), +or [Invoke-Command](../Invoke-Command.md) cmdlets. -This preference variable is set on the local computer, but it specifies a -listener on the remote computer. If the application name that you specify does -not exist on the remote computer, the command to establish the session fails. +The `$PSSessionApplicationName` preference variable is set on the local +computer, but it specifies a listener on the remote computer. If the +application name that you specify doesn't exist on the remote computer, the +command to establish the session fails. -#### \$PSSessionConfigurationName +### \$PSSessionConfigurationName -Specifies the default session configuration that is used for PSSessions +Specifies the default session configuration that is used for **PSSessions** created in the current session. This preference variable is set on the local computer, but it specifies a -session configuration that is located on the remote computer. - -The value of the \$PSSessionConfigurationName variable is a fully -qualified resource URI. +session configuration that's located on the remote computer. -The default value: +The value of the `$PSSessionConfigurationName` variable is a fully qualified +resource URI. -http://schemas.microsoft.com/PowerShell/microsoft.PowerShell - -indicates the Microsoft.PowerShell session configuration on the remote -computer. +The default value +`http://schemas.microsoft.com/PowerShell/microsoft.PowerShell` indicates the +**Microsoft.PowerShell** session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: -http://schemas.microsoft.com/PowerShell/ +`http://schemas.microsoft.com/PowerShell/` -You can override the default and select a different session configuration for -a particular session by using the ConfigurationName parameter of the -New-PSSession, `Enter-PSSession` or `Invoke-Command` cmdlets. +You can override the default and select a different session configuration for a +particular session by using the **ConfigurationName** parameter of the +`New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote -computer. If it does not, the command to create a session that uses the -session configuration fails. +computer. If it doesn't, the command to create a session that uses the session +configuration fails. -This preference variable does not determine which local session configurations +This preference variable doesn't determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. -#### \$PSSessionOption +### \$PSSessionOption Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. -The \$PSSessionOption variable contains a PSSessionOption object -(System.Management.Automation.Remoting.PSSessionObject). Each property of the -object represents a session option. For example, the NoCompression property -turns of data compression during the session. +The `$PSSessionOption` variable contains a **PSSessionOption** object. For more +information, see +[System.Management.Automation.Remoting.PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption). +Each property of the object represents a session option. For example, the +**NoCompression** property turns of data compression during the session. -By default, the \$PSSessionOption variable contains a PSSessionOption object -with the default values for all options, as shown below. +By default, the `$PSSessionOption` variable contains a **PSSessionOption** +object with the default values for all options, as shown below. -```output +```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False @@ -1128,376 +1004,473 @@ CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 ``` -For descriptions of these options, see the help topic for the -`New-PSSessionOption` cmdlet. - -To change the value of the \$PSSessionOption preference variable, use the -New-PSSessionOption cmdlet to create a PSSessionOption object with the option -values you prefer. Save the output in a variable called \$PSSessionOption. +For descriptions of these options and more information, see [New-PSSessionOption](../New-PSSessionOption.md). +For more information about remote commands and sessions, see [about_Remote](about_Remote.md) +and [about_PSSessions](about_PSSessions.md). -For example, +To change the value of the `$PSSessionOption` preference variable, use the +`New-PSSessionOption` cmdlet to create a **PSSessionOption** object with the +option values you prefer. Save the output in a variable called +`$PSSessionOption`. ```powershell $PSSessionOption = New-PSSessionOption -NoCompression ``` -To use the \$PSSessionOption preference variable in every PowerShell session, -add a New-PSSessionOption command that creates the \$PSSessionOption variable -to your PowerShell profile. +To use the `$PSSessionOption` preference variable in every PowerShell session, +add a `New-PSSessionOption` command that creates the `$PSSessionOption` +variable to your PowerShell profile. For more information, see [about_Profiles](about_Profiles.md). -You can also set custom options for a particular remote session. The options -that you set take precedence over the system defaults and the value of the -\$PSSessionOption preference variable. +You can set custom options for a particular remote session. The options that +you set take precedence over the system defaults and the value of the +`$PSSessionOption` preference variable. -To set custom session options, use the New-PSSessionOption cmdlet to create a -PSSessionOption object. Then, use the PSSessionOption object as the value of -the SessionOption parameter in cmdlets that create a session, such as -New-PSSession, Enter-PSSession, and Invoke-Command. +To set custom session options, use the `New-PSSessionOption` cmdlet to create a +**PSSessionOption** object. Then, use the **PSSessionOption** object as the +value of the **SessionOption** parameter in cmdlets that create a session, such +as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. -For more information about the New-PSSessionOption cmdlet, see the help topic -for `New-PSSessionOption`. For more information about remote commands and -sessions, see [about_Remote](about_Remote.md) and -[about_PSSessions](about_PSSessions.md). For more information about using a -profile, see [about_Profiles](about_Profiles.md). - -#### \$VerbosePreference +### \$VerbosePreference Determines how PowerShell responds to verbose messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Verbose -cmdlet. Typically, verbose messages describe the actions performed to execute -a command. +cmdlet, or provider, such as the messages generated by the [Write-Verbose](../../Microsoft.PowerShell.Utility/Write-Verbose.md) +cmdlet. Verbose messages describe the actions performed to execute a command. -By default, verbose messages are not displayed, but you can change this -behavior by changing the value of \$VerbosePreference. +By default, verbose messages aren't displayed, but you can change this behavior +by changing the value of `$VerbosePreference`. -You can also use the Verbose common parameter of a cmdlet to display or hide -the verbose messages for a specific command. For more information, type: -"get-help about_commonparameters". +You can use the **Verbose** common parameter of a cmdlet to display or hide the +verbose messages for a specific command. For more information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the verbose message and an error message and then stops +- **Stop**: Displays the verbose message and an error message and then stops + executing. +- **Inquire**: Displays the verbose message and then displays a prompt that + asks you whether you want to continue. +- **Continue**: Displays the verbose message and then continues with execution. +- **SilentlyContinue**: (Default) Doesn't display the verbose message. Continues executing. -- Inquire: Displays the verbose message and then displays a prompt that asks - you whether you want to continue. -- Continue: Displays the verbose message and then continues with execution. -- SilentlyContinue: Does not display the verbose message. Continues - executing. (Default) -### EXAMPLES +#### Examples -These examples show the effect of the different values of \$VerbosePreference -and the use of the Verbose common parameter to override the preference value. +These examples show the effect of the different values of `$VerbosePreference` +and the **Verbose** parameter to override the preference value. -This example shows the effect of the SilentlyContinue value, which is the -default. +This example shows the effect of the **SilentlyContinue** value, that is the +default. The command uses the **Message** parameter, but doesn't write a +message to the PowerShell console. ```powershell -PS> $VerbosePreference # Find the current value. -SilentlyContinue +Write-Verbose -Message "Verbose message test." +``` -PS> # Write a verbose message. -PS> Write-Verbose "Verbose message test." -PS> # Message is not displayed. +When the **Verbose** parameter is used, the message is written. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose +```powershell +Write-Verbose -Message "Verbose message test." -Verbose +``` + +```Output VERBOSE: Verbose message test. ``` -This example shows the effect of the Continue value. +This example shows the effect of the **Continue** value. The +`$VerbosePreference` variable is set to **Continue** and the message is +displayed. ```powershell -PS> # Change the value to Continue. -PS> $VerbosePreference = "Continue" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Continue" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -PS> # Message is displayed. +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Continue** value. The message isn't displayed. -PS> # Use the Verbose parameter with a value of $false. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Stop value. +This example shows the effect of the **Stop** value. The `$VerbosePreference` +variable is set to **Stop** and the message is displayed. The command is +stopped. ```powershell -PS> # Change the value to Stop. -PS> $VerbosePreference = "Stop" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Stop" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. -Write-Verbose : Command execution stopped because the shell variable -"VerbosePreference" is set to Stop. -At line:1 char:14 -+ Write-Verbose <<<< "Verbose message test." +Write-Verbose : The running command stopped because the preference variable + "VerbosePreference" or common parameter is set to Stop: Verbose message test. +At line:1 char:1 ++ Write-Verbose -Message "Verbose message test." +``` -PS> # Use the Verbose parameter with a value of $false -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> # Message is not displayed. +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Stop** value. The message isn't displayed. + +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -This example shows the effect of the Inquire value. +This example shows the effect of the **Inquire** value. The +`$VerbosePreference` variable is set to **Inquire**. The message is displayed +and the user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $VerbosePreference = "Inquire" -PS> Write-Verbose "Verbose message test." +$VerbosePreference = "Inquire" +Write-Verbose -Message "Verbose message test." +``` + +```Output VERBOSE: Verbose message test. + Confirm Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): +``` + +This example uses the **Verbose** parameter with a value of `$false` that +overrides the **Inquire** value. The user isn't prompted and the message isn't +displayed. -PS> # Use the Verbose parameter. -PS> Write-Verbose "Verbose message test." -verbose:$false -PS> #Message is not displayed. +```powershell +Write-Verbose -Message "Verbose message test." -Verbose:$false ``` -#### \$WarningPreference +### \$WarningPreference Determines how PowerShell responds to warning messages generated by a script, -cmdlet or provider, such as the messages generated by the Write-Warning +cmdlet, or provider, such as the messages generated by the [Write-Warning](../../Microsoft.PowerShell.Utility/Write-Warning.md) cmdlet. -By default, warning messages are displayed and execution continues, but you -can change this behavior by changing the value of \$WarningPreference. +By default, warning messages are displayed and execution continues, but you can +change this behavior by changing the value of `$WarningPreference`. -You can also use the WarningAction common parameter of a cmdlet to determine -how PowerShell responds to warnings from a particular command. For more -information, type: "get-help about_commonparameters". +You can use the **WarningAction** common parameter of a cmdlet to determine how +PowerShell responds to warnings from a particular command. For more +information, see [about_CommonParameters](about_CommonParameters.md). -Valid values: +The valid values are as follows: -- Stop: Displays the warning message and an error message and then stops +- **Stop**: Displays the warning message and an error message and then stops executing. -- Inquire: Displays the warning message and then prompts for permission to +- **Inquire**: Displays the warning message and then prompts for permission to continue. -- Continue: Displays the warning message and then (Default) continues +- **Continue**: (Default) Displays the warning message and then continues executing. -- SilentlyContinue: Does not display the warning message. Continues +- **SilentlyContinue**: Doesn't display the warning message. Continues executing. -##### EXAMPLES +#### Examples -These examples show the effect of the different values of \$WarningPreference -and the use of the WarningAction common parameter to override the preference -value. +These examples show the effect of the different values of `$WarningPreference`. +The **WarningAction** parameter overrides the preference value. -This example shows the effect of the Continue value, which is the default. +This example shows the effect of the default value, **Continue**. ```powershell -PS> $WarningPreference # Find the current value. -Continue -PS> Write-Warning "This action can delete data." +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. +``` -PS> # Use the WarningAction parameter to suppress the warning -PS> Write-Warning "This action can delete data." -warningaction ` - silentlycontinue +This example uses the **WarningAction** parameter with the value +**SilentlyContinue** to suppress the warning. The message isn't displayed. + +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the SilentlyContinue value. +This example changes the `$WarningPreference` variable to the +**SilentlyContinue** value. The message isn't displayed. ```powershell -PS> # Change the value to SilentlyContinue. -PS> $WarningPreference = "SilentlyContinue" -PS> Write-Warning "This action can delete data." -PS> # Write a warning message. +$WarningPreference = "SilentlyContinue" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +This example uses the **WarningAction** parameter to stop when a warning is +generated. -PS> # Use the WarningAction to stop when a warning is generated. -PS> Write-Warning "This step can delete data." -WarningAction stop +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Stop +``` + +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." -WarningAction stop +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m -WarningAction Stop ``` -This example shows the effect of the Inquire value. +This example changes the `$WarningPreference` variable to the **Inquire** +value. The user is prompted for confirmation. ```powershell -PS> # Change the value to Inquire. -PS> $WarningPreference = "Inquire" -PS> Write-Warning "This action can delete data." +$WarningPreference = "Inquire" +$m = "This action can delete data." +Write-Warning -Message $m +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): y -PS> +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): +``` + +This example uses the **WarningAction** parameter with the value +**SilentlyContinue**. The command continues to execute and no message is +displayed. -PS> # Use the WarningAction to continue without stopping. -PS> Write-Warning "This step can delete data." -warningaction ` - silentlycontinue +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction SilentlyContinue ``` -This example shows the effect of the Stop value. +This example changes the `$WarningPreference` value to **Stop**. ```powershell -PS> # Change the value to Stop. -PS> $WarningPreference = "Stop" +$WarningPreference = "Stop" +$m = "This action can delete data." +Write-Warning -Message $m +``` -PS> Write-Warning "This action can delete data." +```Output WARNING: This action can delete data. -Write-Warning : Command execution stopped because the shell variable -"WarningPreference" is set to Stop. -At line:1 char:14 -+ Write-Warning <<<< "This action can delete data." +Write-Warning : The running command stopped because the preference variable + "WarningPreference" or common parameter is set to Stop: + This action can delete data. +At line:1 char:1 ++ Write-Warning -Message $m +``` + +This example uses the **WarningAction** with the **Inquire** value. The user is +prompted when a warning occurs. -PS> # Use the WarningAction to ask when a warning occurs. -PS> Write-Warning "This action can delete data." -warningaction inquire +```powershell +$m = "This action can delete data." +Write-Warning -Message $m -WarningAction Inquire +``` + +```Output WARNING: This action can delete data. Confirm Continue with this operation? -[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend -[?] Help (default is "Y"): +[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"): ``` -#### \$WhatIfPreference +### \$WhatIfPreference + +Determines whether **WhatIf** is automatically enabled for every command that +supports it. When **WhatIf** is enabled, the cmdlet reports the expected effect +of the command, but doesn't execute the command. -Determines whether WhatIf is automatically enabled for every command that -supports it. When WhatIf is enabled, the cmdlet reports the expected effect of -the command, but does not execute the command. +The valid values are as follows: -Valid values: +- **False** (**0**, not enabled): (Default) **WhatIf** isn't automatically + enabled. To enable it manually, use the cmdlet's **WhatIf** parameter. +- **True** (**1**, enabled): **WhatIf** is automatically enabled on any command + that supports it. Users can use the **WhatIf** parameter with a value of + **False** to disable it manually, such as `-WhatIf:$false`. -- 0: WhatIf is not automatically enabled. To (Default) enable it manually, - use the WhatIf parameter of the command. -- 1: WhatIf is automatically enabled on any command that supports it. Users - can use the WhatIf command with a value of False to disable it manually - (WhatIf:\$false). +#### Examples -When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the -command, instead of executing the command. For example, instead of deleting -the test.txt file in response to a `Remove-Item` command, PowerShell reports -what it would delete. A subsequent `Get-Childitem` command confirms that the -file was not deleted. +These examples show the effect of the different values of `$WhatIfPreference`. +They show how to use the **WhatIf** parameter to override the preference value +for a specific command. + +This example shows the effect of the `$WhatIfPreference` variable set to the +default value, **False**. Use `Get-ChildItem` to verify that the file exists. +`Remove-Item` deletes the file. After the file is deleted, you can verify the +deletion with `Get-ChildItem`. ```powershell -PS> # What if: Performing "Remove-Item" on Target "Item: C:\test.txt" -PS> remove-item test.txt -PS> get-childitem test.txt +Get-ChildItem -Path .\test.txt +Remove-Item -Path ./test.txt +``` -Directory: Microsoft.PowerShell.Core\FileSystem::C: +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 9/13/2019 10:53 10 test.txt +``` -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a--- 7/29/2006 7:15 PM 84 test.txt +```powershell +Get-ChildItem -Path .\test.txt ``` -##### EXAMPLES +```Output +Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -File test.txt +``` -These examples show the effect of the different values of \$WhatIfPreference. -They also show how to use the WhatIf cmdlet parameter to override the -preference value for a specific command. +This example shows the effect of using the **WhatIf** parameter when the value +of `$WhatIfPreference` is **False**. -This example shows the effect of the 0 (not enabled) value, which is the -default. +Verify that the file exists. ```powershell -PS> $whatifpreference -0 # Check the current value. +Get-ChildItem -Path .\test2.txt +``` -PS> # Verify that the file exists. -PS> Get-ChildItem test.txt | Format-List FullName -FullName : C:\test.txt +```Output + Directory: C:\Test -PS> remove-item test.txt -PS> # Delete the file. +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` -PS> # Verify that the file is deleted. -PS> Get-ChildItem test.txt | Format-List -Property FullName +Use the **WhatIf** parameter to determine the result of attempting to delete +the file. -Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. -At line:1 char:14 -+ Get-ChildItem <<<< test.txt | Format-List fullname +```powershell +Remove-Item -Path .\test2.txt -WhatIf ``` -This example shows the effect of using the WhatIf parameter when the value -of \$WhatIfPreference is 0. +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +`````` + +Verify that the file wasn't deleted. ```powershell -PS> # Verify that the file exists. -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Get-ChildItem -Path .\test2.txt +``` -PS> # Use the WhatIf parameter -PS> remove-item test2.txt -whatif -What if: Performing operation "Remove File" on Target "C:\test2.txt". +```Output + Directory: C:\Test -PS> # Verify that the file was not deleted -PS> get-childitem test2.txt | Format-List -Property FullName -FullName : C:\test2.txt +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt ``` -This example shows the effect of the 1 (WhatIf enabled) value. When you use -Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that -it would delete, but it does not delete the file. +This example shows the effect of the `$WhatIfPreference` variable set to the +value, **True**. When you use `Remove-Item` to delete a file, the file's path +is displayed, but the file isn't deleted. + +Attempt to delete a file. A message is displayed about what would happen if +`Remove-Item` was run, but the file isn't deleted. ```powershell -PS> $whatifpreference = 1 -PS> $whatifpreference -1 # Change the value. +$WhatIfPreference = "True" +Remove-Item -Path .\test2.txt +``` -PS> # Try to delete a file. -PS> remove-item test.txt -What if: Performing operation "Remove File" on Target "C:\test.txt". +```Output +What if: Performing the operation "Remove File" on target "C:\Test\test2.txt". +``` + +Use `Get-ChildItem` to verify that the file wasn't deleted. -PS> # Verify that the file exists. -PS> get-childitem test.txt | Format-List FullName -FullName : C:\test.txt +```powershell +Get-ChildItem -Path .\test2.txt ``` -This example shows how to delete a file when the value of \$WhatIfPreference -is 1. It uses the WhatIf parameter with a value of \$false. +```Output + Directory: C:\Test + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 2/28/2019 17:06 12 test2.txt +``` + +This example shows how to delete a file when the value of `$WhatIfPreference` +is **True**. It uses the **WhatIf** parameter with a value of `$false`. Use +`Get-ChildItem` to verify the file was deleted. ```powershell -PS> # Use the WhatIf parameter with $false. -PS> remove-item test.txt -whatif:$false +Remove-Item -Path .\test2.txt -WhatIf:$false +Get-ChildItem -Path .\test2.txt +``` + +```Output +Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist. +At line:1 char:1 ++ Get-ChildItem -Path .\test2.txt ``` -This example demonstrates that some cmdlets support WhatIf behavior and others -do not. In this example, in which the value of \$WhatIfPreference is 1 -(enabled), a Get-Process command, which does not support WhatIf, is executed, -but a Stop-Process command performs the WhatIf behavior. You can override the -WhatIf behavior of the Stop-Process command by using the WhatIf parameter with -a value of \$false. +The following are examples of the `Get-Process` cmdlet that doesn't support +**WhatIf** and `Stop-Process` that does support **WhatIf**. The +`$WhatIfPreference` variable's value is **True**. + +`Get-Process` doesn't support **WhatIf**. When the command is executed, it +displays the **Winword** process. ```powershell -PS> # Change the value to 1. -PS> $whatifpreference = 1 +Get-Process -Name Winword +``` -PS> Get-Process winword -A Get-Process command completes. +```Output + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 130 119.84 173.38 8.39 15024 4 WINWORD +``` -Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------- ------ ----- ----- ----- ------ -- ----------- -234 8 6324 15060 154 0.36 2312 WINWORD +`Stop-Process` does support **WhatIf**. The **Winword** process isn't stopped. -PS> # A Stop-Process command uses WhatIf. -PS> stop-process -name winword -What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". +```powershell +Stop-Process -Name Winword +``` + +```Output +What if: Performing the operation "Stop-Process" on target "WINWORD (15024)". +``` + +You can override the `Stop-Process` **WhatIf** behavior by using the **WhatIf** +parameter with a value of `$false`. The **Winword** process is stopped. + +```powershell +Stop-Process -Name Winword -WhatIf:$false +``` + +To verify that the **Winword** process was stopped, use `Get-Process`. -PS> stop-process -name winword -whatif:$false -PS> # WhatIf:$false overrides the preference. +```powershell +Get-Process -Name Winword +``` -PS> # Verify that the process is stopped. -PS> Get-Process winword -Get-Process : Cannot find a process with the name 'winword'. Verify the -process name and call the cmdlet again. -At line:1 char:12 -+ Get-Process <<<< winword +```Output +Get-Process : Cannot find a process with the name "Winword". + Verify the process name and call the cmdlet again. +At line:1 char:1 ++ Get-Process -Name Winword ``` -## SEE ALSO +## See also + +[about_Automatic_Variables](about_Automatic_Variables.md) + +[about_CommonParameters](about_CommonParameters.md) + +[about_Environment_Variables](about_Environment_Variables.md) + +[about_Profiles](about_Profiles.md) + +[about_Remote](about_Remote.md) + +[about_Scopes](about_Scopes.md) -- [about_Automatic_Variables](about_Automatic_Variables.md) -- [about_CommonParameters](about_CommonParameters.md) -- [about_Environment_Variables](about_Environment_Variables.md) -- [about_Profiles](about_Profiles.md) -- [about_Remote](about_Remote.md) -- [about_Scopes](about_Scopes.md) -- [about_Variables](about_Variables.md) +[about_Variables](about_Variables.md)