2

more specific I want to access the value of the ErrorAction parameter from withing the cmdlet.

In powershell everything works as expected

function Get-Test {
    [CmdletBinding()]
    param (

    )
    (Get-Variable|where{$_.Name -eq "ErrorActionPreference"}).Value

}
Get-Test -ErrorAction SilentlyContinue

will output SilentContinue

However the same call in c# will output Continue

    [CmdletBinding]
    [Cmdlet(VerbsCommon.Get,"Test")]
    public class MyClass:PSCmdlet{
        protected override void ProcessRecord(){
            base.ProcessRecord();
            WriteObject(((PSVariable) InvokeCommand.InvokeScript($"Get-Variable|where{{$_.Name -eq 'ErrorActionPreference'}}").First().BaseObject).Value);
        }
    }

it looks like there is no link between the ErrorAction parameter and the ErrorActionPreference when c#. I say this because if I do

$ErrorActionPreference="SilentlyContinue"
Get-Test # c# version

will output SilentlyContinue

0

1 Answer 1

1

Generally, from within (by definition compiled) cmdlets there is no need to determine whether a common parameter was passed or whether its value is implied by a previously set preference variable:

  • Cmdlets can rely on the infrastructure provided by their base class to automatically act appropriately on any common-parameter values passed explicitly or implied by preference variables.

    • E.g., a WriteVerbose() call implicitly adjusts its output behavior based on whether -Verbose was explicitly specified on cmdlet invocation and, in its absence, the value of the $VerbosePreference preference variable in the caller's scope.

In advanced functions - the implemented-in-PowerShell counterparts to compiled cmdlets - explicitly specified common parameters are automaticaly translated into function-scoped preference variables.

  • This is an implementation detail, however, and, regrettably, one that is highly problematic.

  • However, when it does work as intended - in advanced functions originating in the same scope domain as the caller - the effect is the same as in compiled cmdlets: Calls to cmdlets such as Write-Verbose do implicitly pick up both explicitly specified common parameters as well as the caller's preference-variable values (in the latter case via scopes in the same scope domain implicitly seeing variables in the (nearest) ancestral scope).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.