Skip to content

Update PSNativeCommandUseErrorActionPreference example in about_Preference_Variables to use scriptblock scoping #10689

Closed
@rkeithhill

Description

@rkeithhill

Prerequisites

  • Existing Issue: Search the existing issues for this repository. If there is an issue that fits your needs do not file a new one. Subscribe, react, or comment on that issue instead.
  • Descriptive Title: Write the title for this issue as a short synopsis. If possible, provide context. For example, "Document new Get-Foo cmdlet" instead of "New cmdlet."

PowerShell Version

7.3

Summary

The script example in the help topic for $PSNativeCommandUseErrorActionPreference could be simplified to use a scriptblock to reset the variable's value when the scope exits.

Related to PowerShell issue: PowerShell/PowerShell#20034

Details

The following example is given in the current docs:

$definedPreference = $PSNativeCommandUseErrorActionPreference
$PSNativeCommandUseErrorActionPreference = $false
robocopy.exe D:\reports\operational "\\reporting\ops" CY2022Q4.md
$robocopyExitCode = $LASTEXITCODE
if ($robocopyExitCode -gt 8) {
    throw "robocopy failed with exit code $robocopyExitCode"
}
$PSNativeCommandUseErrorActionPreference = $definedPreference

This works but I think the use of a scriptblock would clean this up a bit:

& {
    # Disable $PSNativeCommandUseErrorActionPreference for this scriptblock / call to robocopy
    $PSNativeCommandUseErrorActionPreference = $false
    robocopy.exe D:\reports\operational "\\reporting\ops" CY2022Q4.md
    if ($LASTEXITCODE -gt 8) {
        throw "robocopy failed with exit code $LASTEXITCODE"
    }
}

This will automatically reset the value of $PSNativeCommandUseErrorActionPreference after the scriptblock exits.

Proposed Content Type

About Topic

Proposed Title

N/A

Related Articles

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3#psnativecommanduseerroractionpreference

Metadata

Metadata

Assignees

No one assigned

    Labels

    issue-doc-ideaIssue - request for new content

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions