diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md index bba876d06912..548cfaf7c077 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md @@ -1,7 +1,7 @@ --- description: PowerShell provides the ability to dynamically add new properties and alter the formatting of objects output to the pipeline. Locale: en-US -ms.date: 09/03/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_calculated_properties?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Calculated_Properties @@ -16,12 +16,16 @@ the formatting of objects output to the pipeline. ## Long description Several PowerShell cmdlets transform, group, or process input objects into -output objects using parameters that allow the addition of new properties to +output objects using parameters that allow you to create new properties on those output objects. You can use these parameters to generate new, calculated -properties on output objects based on the values of input objects. The -calculated property is defined by a [hashtable][03] containing key-value pairs -that specify the name of the new property, an expression to calculate the -value, and optional formatting information. +properties on output objects based on the values of input objects. The input +object can be accessed using the `$_` or `$PSItem` automatic variable within +the `Expression` member a calculated property. + +The calculated property is defined as a [hashtable][03] containing key-value +pairs that specify the value of the newly calculated property. Some commands +support other key-value pairs that control how the property is displayed in the +output. ## Supported cmdlets diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_PSItem.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_PSItem.md index fe5f9f382a06..ab77f9a7e5dc 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_PSItem.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_PSItem.md @@ -1,7 +1,7 @@ --- description: The automatic variable that contains the current object in the pipeline object. Locale: en-US -ms.date: 04/17/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_psitem?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_PSItem @@ -14,13 +14,15 @@ The automatic variable that contains the current object in the pipeline object. ## Long description -PowerShell includes the `$PSItem` variable and its alias, `$_`, as -[automatic variables][03] in scriptblocks that process the current object, such -as in the pipeline. This article uses `$PSItem` in the examples, but `$PSItem` -can be replaced with `$_` in every example. +PowerShell includes two [automatic variables][03], `$_` and '$PSItem` that +refer to the current object in the pipeline. -You can use this variable in commands that perform an action on every object in -a pipeline. +`$PSItem` was added to PowerShell in an attempt to provide a clearer meaning to +the variable name. However, in practice, the _dollar sign underscore_ form `$_` +is most commonly used. + +While this article uses `$PSItem` in the examples, `$PSItem` can be replaced +with `$_` in every example. `$_` is the preferred usage. There are a few common use cases for `$PSItem`: @@ -30,16 +32,16 @@ There are a few common use cases for `$PSItem`: cmdlet - In the intrinsic methods **ForEach** and **Where** - with delay-bind scriptblock parameters -- In a `switch` statement's conditional values and associated scriptblocks -- In the `process` block of a function +- In a `switch` statement's conditional values and associated statements +- In the `process` statement block of a function - In a `filter` definition - In the scriptblock of the **ValidateScript** attribute -- In the scriptblock of a `catch` statement +- In the statement block of a `catch` The rest of this article includes examples of using `$PSItem` for these use cases. -## ForEach-Object Process +## ForEach-Object Process parameter The [ForEach-Object][15] cmdlet is designed to operate on objects in the pipeline, executing the **Process** parameter's scriptblock once for every @@ -110,7 +112,7 @@ B In this example, the scriptblock of the **ForEach** method uppercases the current object. Then the scriptblock of the **Where** method returns only `B`. -## Delay-bind ScriptBlock parameters +## Delay-bind scriptblocks [Delay-bind scriptblocks][12] let you use `$PSItem` to define parameters for a pipelined cmdlet before executing it. @@ -119,7 +121,7 @@ pipelined cmdlet before executing it. dir config.log | Rename-Item -NewName { "old_$($_.Name)" } ``` -## Switch statement ScriptBlocks +## Switch statements In [switch statements][13], you can use `$PSItem` in both action scriptblocks and statement condition scriptblocks. @@ -139,23 +141,23 @@ switch ($numbers) { 3 is odd ``` -In this example, the statement condition scriptblock checks whether the current -object is even. If it's even, the associated action scriptblock outputs a +In this example, the condition statement block checks whether the current +object is even. If it's even, the associated action statement block outputs a message indicating the current object is even. -The action scriptblock for the `default` condition outputs a message indicating -the current object is odd. +The action statement block for the `default` condition outputs a message +indicating the current object is odd. -## Function process blocks +## Function process statement blocks When you define a [function][09], you can use `$PSItem` in the `process` block definition but not in the `begin` or `end` block definitions. If you reference `$PSItem` in the `begin` or `end` blocks, the value is `$null` because those blocks don't operate on each object in the pipeline. -When you use `$PSItem` in the `process` block definition, the value is the -value is the current object if the function is called in the pipeline and -otherwise `$null`. +When you use `$PSItem` in the `process` statement block definition, the value +is the current object if the function is called in the pipeline and otherwise +`$null`. ```powershell function Add-One { @@ -173,9 +175,10 @@ function Add-One { > [!TIP] > While you can use `$PSItem` in [advanced functions][08], there's little -> reason to do so. If you intend to receive input from the pipeline, -> it's best to define parameters with one of the `ValueFromPipeline*` arguments -> for the [Parameter][06] attribute. +> reason to do so. If you intend to receive input from the pipeline, it's best +> to define parameters with using either the `ValueFromPipeline` or +> `ValueFromPipelineByPropertyName` arguments in the [Parameter][06] +> attribute. Using the **Parameter** attribute and cmdlet binding for advanced functions makes the implementation more explicit and predictable than processing the @@ -354,23 +357,23 @@ value isn't even. The `Add-EvenNumber` function adds the valid input numbers and returns the total. -## The `catch` statement ScriptBlock +## The `catch` statement block -Within a `catch` block, the current error can be accessed using `$PSItem`. The +Within a `catch` statement block, `$PSItem` contains the current error. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } catch { Write-Host "An error occurred:" - Write-Host $_ + Write-Host $PSItem } ``` Running this script returns the following result: ```Output -An Error occurred: +An error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. @@ -379,6 +382,36 @@ was included, verify that the path is correct and try again. For more examples, see the _Accessing exception information_ section in [about_Try_Catch_Finally][14]. +## Changing the value of `$PSItem` + +You can change the value of `$PSItem` by assigning a new value to it. However, +doing so can change the expected behavior of any code that relies on `$PSItem`. +Consider the following example. Normally, the `switch` statement would process +all values in the array `$names`. Because the value of `$PSItem` is changed +inside the action statement block, the `switch` statement processes only the +first value. + +```powershell +$names = 'Alice', 'Charlie' +switch ($names) { + Alice { "$PSItem says 'Hello!'"; $PSItem = 'Bob' } + Bob { "$PSItem says 'Goodbye.'"; $PSItem = 'Charlie'; break } + Charlie { "$PSItem says 'How are you?'" } +} +``` + +When the `switch` statement evaluates the first value, `Alice`, it matches the +first condition and executes the associated action statement block. Inside that +block, the value of `$PSItem` is changed to `Bob`, which also affects the +evaluation of the `switch` statement. + +```Output +Alice says 'Hello!' +Bob says 'Goodbye.' +``` + +You should avoid changing the value of `$PSItem`. + ## See also - [about_Arrays][01] diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md index 4b27cd924d85..f560fc5b38a7 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 07/05/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Trap @@ -28,10 +28,10 @@ following ways: the default. > [!NOTE] - > When the terminating error occurs in a subordinate script block, such as + > When the terminating error occurs in a subordinate statement block, such as > an `if` statement or `foreach` loop, the statements in the `trap` block are > run and execution continues at the next statement outside the subordinate - > script block. + > block. - Display the error and abort execution of the script or function containing the `trap` using `break` in the `trap` statement. @@ -42,7 +42,7 @@ following ways: The statement list of the `trap` can include multiple conditions or function calls. A `trap` can write logs, test conditions, or even run another program. -### Syntax +## Syntax The `trap` statement has the following syntax: @@ -59,7 +59,7 @@ types of errors the `trap` catches. A script or command can have multiple `trap` statements. `trap` statements can appear anywhere in the script or command. -### Trapping all terminating errors +## Trapping all terminating errors When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If @@ -103,7 +103,7 @@ At line:3 char:5 ``` The following example includes a `trap` statement that displays the error by -using the `$_` automatic variable: +using the `$_` or `$PSItem` automatic variable: ```powershell function TrapTest { @@ -134,17 +134,16 @@ At line:3 char:5 ``` > [!IMPORTANT] -> `trap` statements may be defined anywhere within a given script block, but -> always apply to all statements in that script block. At runtime, `trap` +> `trap` statements can be defined anywhere within a given scriptblock, but +> always apply to all statements in that scriptblock. At runtime, `trap` > statements in a block are defined before any other statements are executed. -> In JavaScript, this is known as -> [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means -> that `trap` statements apply to all statements in that block even if +> In other languages, such as JavaScript, this is known as [hoisting][06]. This +> means that `trap` statements apply to all statements in that block even if > execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. -### Trapping specific errors +## Trapping specific errors A script or command can have multiple `trap` statements. A `trap` can be defined to handle specific errors. @@ -201,7 +200,7 @@ System.Management.Automation.CommandNotFoundException You can have more than one `trap` statement in a script. Only one `trap` statement can trap each error type. When a terminating error occurs, PowerShell searches for the `trap` with the most specific match, starting in the current -script block of execution. +scriptblock of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` @@ -262,13 +261,13 @@ The attempt to divide by zero doesn't create a **CommandNotFoundException** error. The other `trap` statement, which traps any terminating error, traps the divide by zero error. -### Trapping errors in a script block +## Trapping errors in a scriptblock By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement block after the location of the error. -For example, when a terminating error occurs in an `foreach` statement, the +For example, when a terminating error occurs in a `foreach` statement, the `trap` statement is run and execution continues at the next statement after the `foreach` block, not within the `foreach` block. @@ -302,16 +301,16 @@ after loop In the output, you can see the loops continue until the last iteration. When the script tries to divide 1 by 0, PowerShell throws a terminating error. The -script skips the rest of the `foreach` script block, runs the `try` statement, -and continues after the `foreach` script block. +script skips the rest of the `foreach` statement, runs the `try` statement, +and continues after the `foreach` statement. -### Trapping errors and scope +## Trapping errors and scope -If a terminating error occurs in the same script block as the `trap` statement, +If a terminating error occurs in the same scriptblock as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a -different script block from the error, execution continues at the next -statement that's in the same script block as the `trap` statement. +different scriptblock from the error, execution continues at the next +statement that's in the same scriptblock as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -387,7 +386,7 @@ back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first -> `trap` defined lexically (highest in the script block) is used. +> `trap` defined lexically (highest in the scriptblock) is used. In the following example, only the `trap` with `whoops 1` runs. @@ -402,7 +401,7 @@ trap { 'whoops 2'; continue } > statement inside a function or dot sourced script, when the function or dot > sourced script exits, all `trap` statements inside are removed. -### Using the break and continue keywords +## Using the break and continue keywords You can use the `break` and `continue` keywords in a `trap` statement to determine whether a script or command continues to run after a terminating @@ -481,11 +480,11 @@ statement runs. No error is written to the error stream. ## Notes `trap` statements provide a way to ensure all terminating errors within a -script block are handled. For more finer-grained error handling, use -`try`/`catch` blocks where traps are defined using `catch` statements. The +scriptblock are handled. For more fine-grained error handling, use +`try/catch` blocks where traps are defined using `catch` statements. The `catch` statements only apply to the code inside the associated `try` statement. For more information, see -[about_Try_Catch_Finally](about_Try_Catch_Finally.md). +[about_Try_Catch_Finally][05]. ## See also diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md index 72f729e00bdd..95009158ef97 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md @@ -1,7 +1,7 @@ --- description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors. Locale: en-US -ms.date: 05/14/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Try_Catch_Finally @@ -189,8 +189,8 @@ any parent scope has a matching `catch` block. ## Accessing exception information -Within a `catch` block, the current error can be accessed using `$_`, which is -also known as `$PSItem`. The object is of type **ErrorRecord**. +Within a `catch` block, the current error can be accessed using the `$_` or +`$PSItem` automatic variable. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } diff --git a/reference/7.4/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md b/reference/7.4/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md index 7f3209fa27d2..78e9da175a88 100644 --- a/reference/7.4/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md +++ b/reference/7.4/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md @@ -1,7 +1,7 @@ --- description: PowerShell provides the ability to dynamically add new properties and alter the formatting of objects output to the pipeline. Locale: en-US -ms.date: 09/03/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_calculated_properties?view=powershell-7.4&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Calculated_Properties @@ -16,12 +16,16 @@ the formatting of objects output to the pipeline. ## Long description Several PowerShell cmdlets transform, group, or process input objects into -output objects using parameters that allow the addition of new properties to +output objects using parameters that allow you to create new properties on those output objects. You can use these parameters to generate new, calculated -properties on output objects based on the values of input objects. The -calculated property is defined by a [hashtable][03] containing key-value pairs -that specify the name of the new property, an expression to calculate the -value, and optional formatting information. +properties on output objects based on the values of input objects. The input +object can be accessed using the `$_` or `$PSItem` automatic variable within +the `Expression` member a calculated property. + +The calculated property is defined as a [hashtable][03] containing key-value +pairs that specify the value of the newly calculated property. Some commands +support other key-value pairs that control how the property is displayed in the +output. ## Supported cmdlets diff --git a/reference/7.4/Microsoft.PowerShell.Core/About/about_PSItem.md b/reference/7.4/Microsoft.PowerShell.Core/About/about_PSItem.md index 1fe68338cced..d1b0c1832cf7 100644 --- a/reference/7.4/Microsoft.PowerShell.Core/About/about_PSItem.md +++ b/reference/7.4/Microsoft.PowerShell.Core/About/about_PSItem.md @@ -1,7 +1,7 @@ --- description: The automatic variable that contains the current object in the pipeline object. Locale: en-US -ms.date: 01/31/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_psitem?view=powershell-7.4&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_PSItem @@ -14,13 +14,15 @@ The automatic variable that contains the current object in the pipeline object. ## Long description -PowerShell includes the `$PSItem` variable and its alias, `$_`, as -[automatic variables][03] in scriptblocks that process the current object, such -as in the pipeline. This article uses `$PSItem` in the examples, but `$PSItem` -can be replaced with `$_` in every example. +PowerShell includes two [automatic variables][03], `$_` and '$PSItem` that +refer to the current object in the pipeline. -You can use this variable in commands that perform an action on every object in -a pipeline. +`$PSItem` was added to PowerShell in an attempt to provide a clearer meaning to +the variable name. However, in practice, the _dollar sign underscore_ form `$_` +is most commonly used. + +While this article uses `$PSItem` in the examples, `$PSItem` can be replaced +with `$_` in every example. `$_` is the preferred usage. There are a few common use cases for `$PSItem`: @@ -30,17 +32,17 @@ There are a few common use cases for `$PSItem`: cmdlet - In the intrinsic methods **ForEach** and **Where** - with delay-bind scriptblock parameters -- In a `switch` statement's conditional values and associated scriptblocks -- In the `process` block of a function +- In a `switch` statement's conditional values and associated statements +- In the `process` statement block of a function - In a `filter` definition - In the scriptblock of the **ValidateScript** attribute -- In the scriptblock of a `catch` statement +- In the statement block of a `catch` - In the substitution operand scriptblock of the `-replace` operator The rest of this article includes examples of using `$PSItem` for these use cases. -## ForEach-Object Process +## ForEach-Object Process parameter The [ForEach-Object][15] cmdlet is designed to operate on objects in the pipeline, executing the **Process** parameter's scriptblock once for every @@ -111,7 +113,7 @@ B In this example, the scriptblock of the **ForEach** method uppercases the current object. Then the scriptblock of the **Where** method returns only `B`. -## Delay-bind ScriptBlock parameters +## Delay-bind scriptblocks [Delay-bind scriptblocks][12] let you use `$PSItem` to define parameters for a pipelined cmdlet before executing it. @@ -120,7 +122,7 @@ pipelined cmdlet before executing it. dir config.log | Rename-Item -NewName { "old_$($_.Name)" } ``` -## Switch statement ScriptBlocks +## Switch statements In [switch statements][13], you can use `$PSItem` in both action scriptblocks and statement condition scriptblocks. @@ -140,23 +142,23 @@ switch ($numbers) { 3 is odd ``` -In this example, the statement condition scriptblock checks whether the current -object is even. If it's even, the associated action scriptblock outputs a +In this example, the condition statement block checks whether the current +object is even. If it's even, the associated action statement block outputs a message indicating the current object is even. -The action scriptblock for the `default` condition outputs a message indicating -the current object is odd. +The action statement block for the `default` condition outputs a message +indicating the current object is odd. -## Function process blocks +## Function process statement blocks When you define a [function][09], you can use `$PSItem` in the `process` block definition but not in the `begin` or `end` block definitions. If you reference `$PSItem` in the `begin` or `end` blocks, the value is `$null` because those blocks don't operate on each object in the pipeline. -When you use `$PSItem` in the `process` block definition, the value is the -value is the current object if the function is called in the pipeline and -otherwise `$null`. +When you use `$PSItem` in the `process` statement block definition, the value +is the current object if the function is called in the pipeline and otherwise +`$null`. ```powershell function Add-One { @@ -174,9 +176,10 @@ function Add-One { > [!TIP] > While you can use `$PSItem` in [advanced functions][08], there's little -> reason to do so. If you intend to receive input from the pipeline, -> it's best to define parameters with one of the `ValueFromPipeline*` arguments -> for the [Parameter][06] attribute. +> reason to do so. If you intend to receive input from the pipeline, it's best +> to define parameters with using either the `ValueFromPipeline` or +> `ValueFromPipelineByPropertyName` arguments in the [Parameter][06] +> attribute. Using the **Parameter** attribute and cmdlet binding for advanced functions makes the implementation more explicit and predictable than processing the @@ -353,23 +356,23 @@ value isn't even. The `Add-EvenNumber` function adds the valid input numbers and returns the total. -## The `catch` statement ScriptBlock +## The `catch` statement block -Within a `catch` block, the current error can be accessed using `$PSItem`. The +Within a `catch` statement block, `$PSItem` contains the current error. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } catch { Write-Host "An error occurred:" - Write-Host $_ + Write-Host $PSItem } ``` Running this script returns the following result: ```Output -An Error occurred: +An error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. @@ -378,7 +381,7 @@ was included, verify that the path is correct and try again. For more examples, see the _Accessing exception information_ section in [about_Try_Catch_Finally][14]. -## The `-replace` operator's substitution ScriptBlock +## The `-replace` operator's substitution scriptblock Starting in PowerShell 6, you can use `$PSItem` when calling the [-replace][04] operator and defining a [substitution scriptblock][05]. When you do, the value @@ -397,6 +400,36 @@ In this example, the substitution scriptblock replaces the original date string with the default format for the current culture by casting the value to **datetime**. +## Changing the value of `$PSItem` + +You can change the value of `$PSItem` by assigning a new value to it. However, +doing so can change the expected behavior of any code that relies on `$PSItem`. +Consider the following example. Normally, the `switch` statement would process +all values in the array `$names`. Because the value of `$PSItem` is changed +inside the action statement block, the `switch` statement processes only the +first value. + +```powershell +$names = 'Alice', 'Charlie' +switch ($names) { + Alice { "$PSItem says 'Hello!'"; $PSItem = 'Bob' } + Bob { "$PSItem says 'Goodbye.'"; $PSItem = 'Charlie'; break } + Charlie { "$PSItem says 'How are you?'" } +} +``` + +When the `switch` statement evaluates the first value, `Alice`, it matches the +first condition and executes the associated action statement block. Inside that +block, the value of `$PSItem` is changed to `Bob`, which also affects the +evaluation of the `switch` statement. + +```Output +Alice says 'Hello!' +Bob says 'Goodbye.' +``` + +You should avoid changing the value of `$PSItem`. + ## See also - [about_Arrays][01] diff --git a/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md index b0d147f4f059..3867f3b5e570 100644 --- a/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 07/05/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.4&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Trap @@ -28,10 +28,10 @@ following ways: the default. > [!NOTE] - > When the terminating error occurs in a subordinate script block, such as + > When the terminating error occurs in a subordinate statement block, such as > an `if` statement or `foreach` loop, the statements in the `trap` block are > run and execution continues at the next statement outside the subordinate - > script block. + > block. - Display the error and abort execution of the script or function containing the `trap` using `break` in the `trap` statement. @@ -42,7 +42,7 @@ following ways: The statement list of the `trap` can include multiple conditions or function calls. A `trap` can write logs, test conditions, or even run another program. -### Syntax +## Syntax The `trap` statement has the following syntax: @@ -59,7 +59,7 @@ types of errors the `trap` catches. A script or command can have multiple `trap` statements. `trap` statements can appear anywhere in the script or command. -### Trapping all terminating errors +## Trapping all terminating errors When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If @@ -101,7 +101,7 @@ path is correct and try again. ``` The following example includes a `trap` statement that displays the error by -using the `$_` automatic variable: +using the `$_` or `$PSItem` automatic variable: ```powershell function TrapTest { @@ -130,17 +130,16 @@ path is correct and try again. ``` > [!IMPORTANT] -> `trap` statements may be defined anywhere within a given script block, but -> always apply to all statements in that script block. At runtime, `trap` +> `trap` statements can be defined anywhere within a given scriptblock, but +> always apply to all statements in that scriptblock. At runtime, `trap` > statements in a block are defined before any other statements are executed. -> In JavaScript, this is known as -> [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means -> that `trap` statements apply to all statements in that block even if +> In other languages, such as JavaScript, this is known as [hoisting][06]. This +> means that `trap` statements apply to all statements in that block even if > execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. -### Trapping specific errors +## Trapping specific errors A script or command can have multiple `trap` statements. A `trap` can be defined to handle specific errors. @@ -191,7 +190,7 @@ System.Management.Automation.CommandNotFoundException You can have more than one `trap` statement in a script. Only one `trap` statement can trap each error type. When a terminating error occurs, PowerShell searches for the `trap` with the most specific match, starting in the current -script block of execution. +scriptblock of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` @@ -249,7 +248,7 @@ The attempt to divide by zero doesn't create a **CommandNotFoundException** error. The other `trap` statement, which traps any terminating error, traps the divide by zero error. -### Trapping errors in a script block +## Trapping errors in a scriptblock By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement @@ -287,16 +286,16 @@ after loop In the output, you can see the loops continue until the last iteration. When the script tries to divide 1 by 0, PowerShell throws a terminating error. The -script skips the rest of the `foreach` script block, runs the `try` statement, -and continues after the `foreach` script block. +script skips the rest of the `foreach` statement, runs the `try` statement, +and continues after the `foreach` statement. -### Trapping errors and scope +## Trapping errors and scope -If a terminating error occurs in the same script block as the `trap` statement, +If a terminating error occurs in the same scriptblock as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a -different script block from the error, execution continues at the next -statement that's in the same script block as the `trap` statement. +different scriptblock from the error, execution continues at the next +statement that's in the same scriptblock as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -367,7 +366,7 @@ back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first -> `trap` defined lexically (highest in the script block) is used. +> `trap` defined lexically (highest in the scriptblock) is used. In the following example, only the `trap` with `whoops 1` runs. @@ -382,7 +381,7 @@ trap { 'whoops 2'; continue } > statement inside a function or dot sourced script, when the function or dot > sourced script exits, all `trap` statements inside are removed. -### Using the break and continue keywords +## Using the break and continue keywords You can use the `break` and `continue` keywords in a `trap` statement to determine whether a script or command continues to run after a terminating @@ -459,16 +458,24 @@ statement runs. No error is written to the error stream. ## Notes `trap` statements provide a way to ensure all terminating errors within a -script block are handled. For more finer-grained error handling, use -`try`/`catch` blocks where traps are defined using `catch` statements. The +scriptblock are handled. For more fine-grained error handling, use +`try/catch` blocks where traps are defined using `catch` statements. The `catch` statements only apply to the code inside the associated `try` statement. For more information, see -[about_Try_Catch_Finally](about_Try_Catch_Finally.md). +[about_Try_Catch_Finally][05]. ## See also -- [about_Break](about_Break.md) -- [about_Continue](about_Continue.md) -- [about_Scopes](about_Scopes.md) -- [about_Throw](about_Throw.md) -- [about_Try_Catch_Finally](about_Try_Catch_Finally.md) +- [about_Break][01] +- [about_Continue][02] +- [about_Scopes][03] +- [about_Throw][04] +- [about_Try_Catch_Finally][05] + + +[01]: about_Break.md +[02]: about_Continue.md +[03]: about_Scopes.md +[04]: about_Throw.md +[05]: about_Try_Catch_Finally.md +[06]: https://wikipedia.org/wiki/JavaScript_syntax#hoisting diff --git a/reference/7.4/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md b/reference/7.4/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md index 702ffc7f1765..991e4460fb9e 100644 --- a/reference/7.4/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md +++ b/reference/7.4/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md @@ -1,7 +1,7 @@ --- description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors. Locale: en-US -ms.date: 05/14/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.4&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Try_Catch_Finally @@ -189,8 +189,8 @@ any parent scope has a matching `catch` block. ## Accessing exception information -Within a `catch` block, the current error can be accessed using `$_`, which is -also known as `$PSItem`. The object is of type **ErrorRecord**. +Within a `catch` block, the current error can be accessed using the `$_` or +`$PSItem` automatic variable. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } diff --git a/reference/7.5/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md b/reference/7.5/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md index eeb07fc9e7b2..3d69471f9338 100644 --- a/reference/7.5/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md +++ b/reference/7.5/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md @@ -1,7 +1,7 @@ --- description: PowerShell provides the ability to dynamically add new properties and alter the formatting of objects output to the pipeline. Locale: en-US -ms.date: 09/03/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_calculated_properties?view=powershell-7.5&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Calculated_Properties @@ -16,12 +16,16 @@ the formatting of objects output to the pipeline. ## Long description Several PowerShell cmdlets transform, group, or process input objects into -output objects using parameters that allow the addition of new properties to +output objects using parameters that allow you to create new properties on those output objects. You can use these parameters to generate new, calculated -properties on output objects based on the values of input objects. The -calculated property is defined by a [hashtable][03] containing key-value pairs -that specify the name of the new property, an expression to calculate the -value, and optional formatting information. +properties on output objects based on the values of input objects. The input +object can be accessed using the `$_` or `$PSItem` automatic variable within +the `Expression` member a calculated property. + +The calculated property is defined as a [hashtable][03] containing key-value +pairs that specify the value of the newly calculated property. Some commands +support other key-value pairs that control how the property is displayed in the +output. ## Supported cmdlets diff --git a/reference/7.5/Microsoft.PowerShell.Core/About/about_PSItem.md b/reference/7.5/Microsoft.PowerShell.Core/About/about_PSItem.md index 6991c77f78e9..d90905e0c373 100644 --- a/reference/7.5/Microsoft.PowerShell.Core/About/about_PSItem.md +++ b/reference/7.5/Microsoft.PowerShell.Core/About/about_PSItem.md @@ -1,7 +1,7 @@ --- description: The automatic variable that contains the current object in the pipeline object. Locale: en-US -ms.date: 01/31/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_psitem?view=powershell-7.5&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_PSItem @@ -14,13 +14,15 @@ The automatic variable that contains the current object in the pipeline object. ## Long description -PowerShell includes the `$PSItem` variable and its alias, `$_`, as -[automatic variables][03] in scriptblocks that process the current object, such -as in the pipeline. This article uses `$PSItem` in the examples, but `$PSItem` -can be replaced with `$_` in every example. +PowerShell includes two [automatic variables][03], `$_` and '$PSItem` that +refer to the current object in the pipeline. -You can use this variable in commands that perform an action on every object in -a pipeline. +`$PSItem` was added to PowerShell in an attempt to provide a clearer meaning to +the variable name. However, in practice, the _dollar sign underscore_ form `$_` +is most commonly used. + +While this article uses `$PSItem` in the examples, `$PSItem` can be replaced +with `$_` in every example. `$_` is the preferred usage. There are a few common use cases for `$PSItem`: @@ -30,17 +32,17 @@ There are a few common use cases for `$PSItem`: cmdlet - In the intrinsic methods **ForEach** and **Where** - with delay-bind scriptblock parameters -- In a `switch` statement's conditional values and associated scriptblocks -- In the `process` block of a function +- In a `switch` statement's conditional values and associated statements +- In the `process` statement block of a function - In a `filter` definition - In the scriptblock of the **ValidateScript** attribute -- In the scriptblock of a `catch` statement +- In the statement block of a `catch` - In the substitution operand scriptblock of the `-replace` operator The rest of this article includes examples of using `$PSItem` for these use cases. -## ForEach-Object Process +## ForEach-Object Process parameter The [ForEach-Object][15] cmdlet is designed to operate on objects in the pipeline, executing the **Process** parameter's scriptblock once for every @@ -111,7 +113,7 @@ B In this example, the scriptblock of the **ForEach** method uppercases the current object. Then the scriptblock of the **Where** method returns only `B`. -## Delay-bind ScriptBlock parameters +## Delay-bind scriptblocks [Delay-bind scriptblocks][12] let you use `$PSItem` to define parameters for a pipelined cmdlet before executing it. @@ -120,7 +122,7 @@ pipelined cmdlet before executing it. dir config.log | Rename-Item -NewName { "old_$($_.Name)" } ``` -## Switch statement ScriptBlocks +## Switch statements In [switch statements][13], you can use `$PSItem` in both action scriptblocks and statement condition scriptblocks. @@ -140,23 +142,23 @@ switch ($numbers) { 3 is odd ``` -In this example, the statement condition scriptblock checks whether the current -object is even. If it's even, the associated action scriptblock outputs a +In this example, the condition statement block checks whether the current +object is even. If it's even, the associated action statement block outputs a message indicating the current object is even. -The action scriptblock for the `default` condition outputs a message indicating -the current object is odd. +The action statement block for the `default` condition outputs a message +indicating the current object is odd. -## Function process blocks +## Function process statement blocks When you define a [function][09], you can use `$PSItem` in the `process` block definition but not in the `begin` or `end` block definitions. If you reference `$PSItem` in the `begin` or `end` blocks, the value is `$null` because those blocks don't operate on each object in the pipeline. -When you use `$PSItem` in the `process` block definition, the value is the -value is the current object if the function is called in the pipeline and -otherwise `$null`. +When you use `$PSItem` in the `process` statement block definition, the value +is the current object if the function is called in the pipeline and otherwise +`$null`. ```powershell function Add-One { @@ -174,9 +176,10 @@ function Add-One { > [!TIP] > While you can use `$PSItem` in [advanced functions][08], there's little -> reason to do so. If you intend to receive input from the pipeline, -> it's best to define parameters with one of the `ValueFromPipeline*` arguments -> for the [Parameter][06] attribute. +> reason to do so. If you intend to receive input from the pipeline, it's best +> to define parameters with using either the `ValueFromPipeline` or +> `ValueFromPipelineByPropertyName` arguments in the [Parameter][06] +> attribute. Using the **Parameter** attribute and cmdlet binding for advanced functions makes the implementation more explicit and predictable than processing the @@ -353,23 +356,23 @@ value isn't even. The `Add-EvenNumber` function adds the valid input numbers and returns the total. -## The `catch` statement ScriptBlock +## The `catch` statement block -Within a `catch` block, the current error can be accessed using `$PSItem`. The +Within a `catch` statement block, `$PSItem` contains the current error. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } catch { Write-Host "An error occurred:" - Write-Host $_ + Write-Host $PSItem } ``` Running this script returns the following result: ```Output -An Error occurred: +An error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. @@ -378,7 +381,7 @@ was included, verify that the path is correct and try again. For more examples, see the _Accessing exception information_ section in [about_Try_Catch_Finally][14]. -## The `-replace` operator's substitution ScriptBlock +## The `-replace` operator's substitution scriptblock Starting in PowerShell 6, you can use `$PSItem` when calling the [-replace][04] operator and defining a [substitution scriptblock][05]. When you do, the value @@ -397,6 +400,36 @@ In this example, the substitution scriptblock replaces the original date string with the default format for the current culture by casting the value to **datetime**. +## Changing the value of `$PSItem` + +You can change the value of `$PSItem` by assigning a new value to it. However, +doing so can change the expected behavior of any code that relies on `$PSItem`. +Consider the following example. Normally, the `switch` statement would process +all values in the array `$names`. Because the value of `$PSItem` is changed +inside the action statement block, the `switch` statement processes only the +first value. + +```powershell +$names = 'Alice', 'Charlie' +switch ($names) { + Alice { "$PSItem says 'Hello!'"; $PSItem = 'Bob' } + Bob { "$PSItem says 'Goodbye.'"; $PSItem = 'Charlie'; break } + Charlie { "$PSItem says 'How are you?'" } +} +``` + +When the `switch` statement evaluates the first value, `Alice`, it matches the +first condition and executes the associated action statement block. Inside that +block, the value of `$PSItem` is changed to `Bob`, which also affects the +evaluation of the `switch` statement. + +```Output +Alice says 'Hello!' +Bob says 'Goodbye.' +``` + +You should avoid changing the value of `$PSItem`. + ## See also - [about_Arrays][01] diff --git a/reference/7.5/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.5/Microsoft.PowerShell.Core/About/about_Trap.md index b38eadf81996..37514e43fdc9 100644 --- a/reference/7.5/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.5/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 07/05/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.5&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Trap @@ -28,10 +28,10 @@ following ways: the default. > [!NOTE] - > When the terminating error occurs in a subordinate script block, such as + > When the terminating error occurs in a subordinate statement block, such as > an `if` statement or `foreach` loop, the statements in the `trap` block are > run and execution continues at the next statement outside the subordinate - > script block. + > block. - Display the error and abort execution of the script or function containing the `trap` using `break` in the `trap` statement. @@ -42,7 +42,7 @@ following ways: The statement list of the `trap` can include multiple conditions or function calls. A `trap` can write logs, test conditions, or even run another program. -### Syntax +## Syntax The `trap` statement has the following syntax: @@ -59,7 +59,7 @@ types of errors the `trap` catches. A script or command can have multiple `trap` statements. `trap` statements can appear anywhere in the script or command. -### Trapping all terminating errors +## Trapping all terminating errors When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If @@ -101,7 +101,7 @@ path is correct and try again. ``` The following example includes a `trap` statement that displays the error by -using the `$_` automatic variable: +using the `$_` or `$PSItem` automatic variable: ```powershell function TrapTest { @@ -130,17 +130,16 @@ path is correct and try again. ``` > [!IMPORTANT] -> `trap` statements may be defined anywhere within a given script block, but -> always apply to all statements in that script block. At runtime, `trap` +> `trap` statements can be defined anywhere within a given scriptblock, but +> always apply to all statements in that scriptblock. At runtime, `trap` > statements in a block are defined before any other statements are executed. -> In JavaScript, this is known as -> [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means -> that `trap` statements apply to all statements in that block even if +> In other languages, such as JavaScript, this is known as [hoisting][06]. This +> means that `trap` statements apply to all statements in that block even if > execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. -### Trapping specific errors +## Trapping specific errors A script or command can have multiple `trap` statements. A `trap` can be defined to handle specific errors. @@ -191,7 +190,7 @@ System.Management.Automation.CommandNotFoundException You can have more than one `trap` statement in a script. Only one `trap` statement can trap each error type. When a terminating error occurs, PowerShell searches for the `trap` with the most specific match, starting in the current -script block of execution. +scriptblock of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` @@ -249,7 +248,7 @@ The attempt to divide by zero doesn't create a **CommandNotFoundException** error. The other `trap` statement, which traps any terminating error, traps the divide by zero error. -### Trapping errors in a script block +## Trapping errors in a scriptblock By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement @@ -287,16 +286,16 @@ after loop In the output, you can see the loops continue until the last iteration. When the script tries to divide 1 by 0, PowerShell throws a terminating error. The -script skips the rest of the `foreach` script block, runs the `try` statement, -and continues after the `foreach` script block. +script skips the rest of the `foreach` statement, runs the `try` statement, +and continues after the `foreach` statement. -### Trapping errors and scope +## Trapping errors and scope -If a terminating error occurs in the same script block as the `trap` statement, +If a terminating error occurs in the same scriptblock as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a -different script block from the error, execution continues at the next -statement that's in the same script block as the `trap` statement. +different scriptblock from the error, execution continues at the next +statement that's in the same scriptblock as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -367,7 +366,7 @@ back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first -> `trap` defined lexically (highest in the script block) is used. +> `trap` defined lexically (highest in the scriptblock) is used. In the following example, only the `trap` with `whoops 1` runs. @@ -382,7 +381,7 @@ trap { 'whoops 2'; continue } > statement inside a function or dot sourced script, when the function or dot > sourced script exits, all `trap` statements inside are removed. -### Using the break and continue keywords +## Using the break and continue keywords You can use the `break` and `continue` keywords in a `trap` statement to determine whether a script or command continues to run after a terminating @@ -459,16 +458,24 @@ statement runs. No error is written to the error stream. ## Notes `trap` statements provide a way to ensure all terminating errors within a -script block are handled. For more finer-grained error handling, use -`try`/`catch` blocks where traps are defined using `catch` statements. The +scriptblock are handled. For more fine-grained error handling, use +`try/catch` blocks where traps are defined using `catch` statements. The `catch` statements only apply to the code inside the associated `try` statement. For more information, see -[about_Try_Catch_Finally](about_Try_Catch_Finally.md). +[about_Try_Catch_Finally][05]. ## See also -- [about_Break](about_Break.md) -- [about_Continue](about_Continue.md) -- [about_Scopes](about_Scopes.md) -- [about_Throw](about_Throw.md) -- [about_Try_Catch_Finally](about_Try_Catch_Finally.md) +- [about_Break][01] +- [about_Continue][02] +- [about_Scopes][03] +- [about_Throw][04] +- [about_Try_Catch_Finally][05] + + +[01]: about_Break.md +[02]: about_Continue.md +[03]: about_Scopes.md +[04]: about_Throw.md +[05]: about_Try_Catch_Finally.md +[06]: https://wikipedia.org/wiki/JavaScript_syntax#hoisting diff --git a/reference/7.5/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md b/reference/7.5/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md index ab07de70048c..676b01d71791 100644 --- a/reference/7.5/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md +++ b/reference/7.5/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md @@ -1,7 +1,7 @@ --- description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors. Locale: en-US -ms.date: 05/14/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.5&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Try_Catch_Finally @@ -189,8 +189,8 @@ any parent scope has a matching `catch` block. ## Accessing exception information -Within a `catch` block, the current error can be accessed using `$_`, which is -also known as `$PSItem`. The object is of type **ErrorRecord**. +Within a `catch` block, the current error can be accessed using the `$_` or +`$PSItem` automatic variable. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } diff --git a/reference/7.6/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md b/reference/7.6/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md index 385b74ba2946..c5e59a36d83d 100644 --- a/reference/7.6/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md +++ b/reference/7.6/Microsoft.PowerShell.Core/About/about_Calculated_Properties.md @@ -1,7 +1,7 @@ --- description: PowerShell provides the ability to dynamically add new properties and alter the formatting of objects output to the pipeline. Locale: en-US -ms.date: 09/03/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_calculated_properties?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Calculated_Properties @@ -16,12 +16,16 @@ the formatting of objects output to the pipeline. ## Long description Several PowerShell cmdlets transform, group, or process input objects into -output objects using parameters that allow the addition of new properties to +output objects using parameters that allow you to create new properties on those output objects. You can use these parameters to generate new, calculated -properties on output objects based on the values of input objects. The -calculated property is defined by a [hashtable][03] containing key-value pairs -that specify the name of the new property, an expression to calculate the -value, and optional formatting information. +properties on output objects based on the values of input objects. The input +object can be accessed using the `$_` or `$PSItem` automatic variable within +the `Expression` member a calculated property. + +The calculated property is defined as a [hashtable][03] containing key-value +pairs that specify the value of the newly calculated property. Some commands +support other key-value pairs that control how the property is displayed in the +output. ## Supported cmdlets diff --git a/reference/7.6/Microsoft.PowerShell.Core/About/about_PSItem.md b/reference/7.6/Microsoft.PowerShell.Core/About/about_PSItem.md index eb15e7c24182..54ff15dc93bf 100644 --- a/reference/7.6/Microsoft.PowerShell.Core/About/about_PSItem.md +++ b/reference/7.6/Microsoft.PowerShell.Core/About/about_PSItem.md @@ -1,7 +1,7 @@ --- description: The automatic variable that contains the current object in the pipeline object. Locale: en-US -ms.date: 01/31/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_psitem?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_PSItem @@ -14,13 +14,15 @@ The automatic variable that contains the current object in the pipeline object. ## Long description -PowerShell includes the `$PSItem` variable and its alias, `$_`, as -[automatic variables][03] in scriptblocks that process the current object, such -as in the pipeline. This article uses `$PSItem` in the examples, but `$PSItem` -can be replaced with `$_` in every example. +PowerShell includes two [automatic variables][03], `$_` and '$PSItem` that +refer to the current object in the pipeline. -You can use this variable in commands that perform an action on every object in -a pipeline. +`$PSItem` was added to PowerShell in an attempt to provide a clearer meaning to +the variable name. However, in practice, the _dollar sign underscore_ form `$_` +is most commonly used. + +While this article uses `$PSItem` in the examples, `$PSItem` can be replaced +with `$_` in every example. `$_` is the preferred usage. There are a few common use cases for `$PSItem`: @@ -30,17 +32,17 @@ There are a few common use cases for `$PSItem`: cmdlet - In the intrinsic methods **ForEach** and **Where** - with delay-bind scriptblock parameters -- In a `switch` statement's conditional values and associated scriptblocks -- In the `process` block of a function +- In a `switch` statement's conditional values and associated statements +- In the `process` statement block of a function - In a `filter` definition - In the scriptblock of the **ValidateScript** attribute -- In the scriptblock of a `catch` statement +- In the statement block of a `catch` - In the substitution operand scriptblock of the `-replace` operator The rest of this article includes examples of using `$PSItem` for these use cases. -## ForEach-Object Process +## ForEach-Object Process parameter The [ForEach-Object][15] cmdlet is designed to operate on objects in the pipeline, executing the **Process** parameter's scriptblock once for every @@ -111,7 +113,7 @@ B In this example, the scriptblock of the **ForEach** method uppercases the current object. Then the scriptblock of the **Where** method returns only `B`. -## Delay-bind ScriptBlock parameters +## Delay-bind scriptblocks [Delay-bind scriptblocks][12] let you use `$PSItem` to define parameters for a pipelined cmdlet before executing it. @@ -120,7 +122,7 @@ pipelined cmdlet before executing it. dir config.log | Rename-Item -NewName { "old_$($_.Name)" } ``` -## Switch statement ScriptBlocks +## Switch statements In [switch statements][13], you can use `$PSItem` in both action scriptblocks and statement condition scriptblocks. @@ -140,23 +142,23 @@ switch ($numbers) { 3 is odd ``` -In this example, the statement condition scriptblock checks whether the current -object is even. If it's even, the associated action scriptblock outputs a +In this example, the condition statement block checks whether the current +object is even. If it's even, the associated action statement block outputs a message indicating the current object is even. -The action scriptblock for the `default` condition outputs a message indicating -the current object is odd. +The action statement block for the `default` condition outputs a message +indicating the current object is odd. -## Function process blocks +## Function process statement blocks When you define a [function][09], you can use `$PSItem` in the `process` block definition but not in the `begin` or `end` block definitions. If you reference `$PSItem` in the `begin` or `end` blocks, the value is `$null` because those blocks don't operate on each object in the pipeline. -When you use `$PSItem` in the `process` block definition, the value is the -value is the current object if the function is called in the pipeline and -otherwise `$null`. +When you use `$PSItem` in the `process` statement block definition, the value +is the current object if the function is called in the pipeline and otherwise +`$null`. ```powershell function Add-One { @@ -174,9 +176,10 @@ function Add-One { > [!TIP] > While you can use `$PSItem` in [advanced functions][08], there's little -> reason to do so. If you intend to receive input from the pipeline, -> it's best to define parameters with one of the `ValueFromPipeline*` arguments -> for the [Parameter][06] attribute. +> reason to do so. If you intend to receive input from the pipeline, it's best +> to define parameters with using either the `ValueFromPipeline` or +> `ValueFromPipelineByPropertyName` arguments in the [Parameter][06] +> attribute. Using the **Parameter** attribute and cmdlet binding for advanced functions makes the implementation more explicit and predictable than processing the @@ -353,23 +356,23 @@ value isn't even. The `Add-EvenNumber` function adds the valid input numbers and returns the total. -## The `catch` statement ScriptBlock +## The `catch` statement block -Within a `catch` block, the current error can be accessed using `$PSItem`. The +Within a `catch` statement block, `$PSItem` contains the current error. The object is of type **ErrorRecord**. ```powershell try { NonsenseString } catch { Write-Host "An error occurred:" - Write-Host $_ + Write-Host $PSItem } ``` Running this script returns the following result: ```Output -An Error occurred: +An error occurred: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. @@ -378,7 +381,7 @@ was included, verify that the path is correct and try again. For more examples, see the _Accessing exception information_ section in [about_Try_Catch_Finally][14]. -## The `-replace` operator's substitution ScriptBlock +## The `-replace` operator's substitution scriptblock Starting in PowerShell 6, you can use `$PSItem` when calling the [-replace][04] operator and defining a [substitution scriptblock][05]. When you do, the value @@ -397,6 +400,36 @@ In this example, the substitution scriptblock replaces the original date string with the default format for the current culture by casting the value to **datetime**. +## Changing the value of `$PSItem` + +You can change the value of `$PSItem` by assigning a new value to it. However, +doing so can change the expected behavior of any code that relies on `$PSItem`. +Consider the following example. Normally, the `switch` statement would process +all values in the array `$names`. Because the value of `$PSItem` is changed +inside the action statement block, the `switch` statement processes only the +first value. + +```powershell +$names = 'Alice', 'Charlie' +switch ($names) { + Alice { "$PSItem says 'Hello!'"; $PSItem = 'Bob' } + Bob { "$PSItem says 'Goodbye.'"; $PSItem = 'Charlie'; break } + Charlie { "$PSItem says 'How are you?'" } +} +``` + +When the `switch` statement evaluates the first value, `Alice`, it matches the +first condition and executes the associated action statement block. Inside that +block, the value of `$PSItem` is changed to `Bob`, which also affects the +evaluation of the `switch` statement. + +```Output +Alice says 'Hello!' +Bob says 'Goodbye.' +``` + +You should avoid changing the value of `$PSItem`. + ## See also - [about_Arrays][01] diff --git a/reference/7.6/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.6/Microsoft.PowerShell.Core/About/about_Trap.md index bbfa13a1a1a4..1a59f55c7098 100644 --- a/reference/7.6/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.6/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 07/05/2024 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Trap @@ -28,10 +28,10 @@ following ways: the default. > [!NOTE] - > When the terminating error occurs in a subordinate script block, such as + > When the terminating error occurs in a subordinate statement block, such as > an `if` statement or `foreach` loop, the statements in the `trap` block are > run and execution continues at the next statement outside the subordinate - > script block. + > block. - Display the error and abort execution of the script or function containing the `trap` using `break` in the `trap` statement. @@ -42,7 +42,7 @@ following ways: The statement list of the `trap` can include multiple conditions or function calls. A `trap` can write logs, test conditions, or even run another program. -### Syntax +## Syntax The `trap` statement has the following syntax: @@ -59,7 +59,7 @@ types of errors the `trap` catches. A script or command can have multiple `trap` statements. `trap` statements can appear anywhere in the script or command. -### Trapping all terminating errors +## Trapping all terminating errors When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If @@ -101,7 +101,7 @@ path is correct and try again. ``` The following example includes a `trap` statement that displays the error by -using the `$_` automatic variable: +using the `$_` or `$PSItem` automatic variable: ```powershell function TrapTest { @@ -130,17 +130,16 @@ path is correct and try again. ``` > [!IMPORTANT] -> `trap` statements may be defined anywhere within a given script block, but -> always apply to all statements in that script block. At runtime, `trap` +> `trap` statements can be defined anywhere within a given scriptblock, but +> always apply to all statements in that scriptblock. At runtime, `trap` > statements in a block are defined before any other statements are executed. -> In JavaScript, this is known as -> [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means -> that `trap` statements apply to all statements in that block even if +> In other languages, such as JavaScript, this is known as [hoisting][06]. This +> means that `trap` statements apply to all statements in that block even if > execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. -### Trapping specific errors +## Trapping specific errors A script or command can have multiple `trap` statements. A `trap` can be defined to handle specific errors. @@ -191,7 +190,7 @@ System.Management.Automation.CommandNotFoundException You can have more than one `trap` statement in a script. Only one `trap` statement can trap each error type. When a terminating error occurs, PowerShell searches for the `trap` with the most specific match, starting in the current -script block of execution. +scriptblock of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` @@ -249,7 +248,7 @@ The attempt to divide by zero doesn't create a **CommandNotFoundException** error. The other `trap` statement, which traps any terminating error, traps the divide by zero error. -### Trapping errors in a script block +## Trapping errors in a scriptblock By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement @@ -287,16 +286,16 @@ after loop In the output, you can see the loops continue until the last iteration. When the script tries to divide 1 by 0, PowerShell throws a terminating error. The -script skips the rest of the `foreach` script block, runs the `try` statement, -and continues after the `foreach` script block. +script skips the rest of the `foreach` statement, runs the `try` statement, +and continues after the `foreach` statement. -### Trapping errors and scope +## Trapping errors and scope -If a terminating error occurs in the same script block as the `trap` statement, +If a terminating error occurs in the same scriptblock as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a -different script block from the error, execution continues at the next -statement that's in the same script block as the `trap` statement. +different scriptblock from the error, execution continues at the next +statement that's in the same scriptblock as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -367,7 +366,7 @@ back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first -> `trap` defined lexically (highest in the script block) is used. +> `trap` defined lexically (highest in the scriptblock) is used. In the following example, only the `trap` with `whoops 1` runs. @@ -382,7 +381,7 @@ trap { 'whoops 2'; continue } > statement inside a function or dot sourced script, when the function or dot > sourced script exits, all `trap` statements inside are removed. -### Using the break and continue keywords +## Using the break and continue keywords You can use the `break` and `continue` keywords in a `trap` statement to determine whether a script or command continues to run after a terminating @@ -459,16 +458,24 @@ statement runs. No error is written to the error stream. ## Notes `trap` statements provide a way to ensure all terminating errors within a -script block are handled. For more finer-grained error handling, use -`try`/`catch` blocks where traps are defined using `catch` statements. The +scriptblock are handled. For more fine-grained error handling, use +`try/catch` blocks where traps are defined using `catch` statements. The `catch` statements only apply to the code inside the associated `try` statement. For more information, see -[about_Try_Catch_Finally](about_Try_Catch_Finally.md). +[about_Try_Catch_Finally][05]. ## See also -- [about_Break](about_Break.md) -- [about_Continue](about_Continue.md) -- [about_Scopes](about_Scopes.md) -- [about_Throw](about_Throw.md) -- [about_Try_Catch_Finally](about_Try_Catch_Finally.md) +- [about_Break][01] +- [about_Continue][02] +- [about_Scopes][03] +- [about_Throw][04] +- [about_Try_Catch_Finally][05] + + +[01]: about_Break.md +[02]: about_Continue.md +[03]: about_Scopes.md +[04]: about_Throw.md +[05]: about_Try_Catch_Finally.md +[06]: https://wikipedia.org/wiki/JavaScript_syntax#hoisting diff --git a/reference/7.6/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md b/reference/7.6/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md index 8307953bc6ff..82b449f68137 100644 --- a/reference/7.6/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md +++ b/reference/7.6/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md @@ -1,7 +1,7 @@ --- description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors. Locale: en-US -ms.date: 05/14/2025 +ms.date: 01/13/2026 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: about_Try_Catch_Finally @@ -189,8 +189,8 @@ any parent scope has a matching `catch` block. ## Accessing exception information -Within a `catch` block, the current error can be accessed using `$_`, which is -also known as `$PSItem`. The object is of type **ErrorRecord**. +Within a `catch` block, the current error can be accessed using the `$_` or +`$PSItem` automatic variable. The object is of type **ErrorRecord**. ```powershell try { NonsenseString }