4

Scripts (with CmdletBinding) and cmdlets all have a standard -ErrorAction parameter available when being invoked. Is there a way then, within your script, if indeed you script was invoked with -ErrorAction?

Reason I ask is because I want to know if the automatic variable value for $ErrorActionPreference, as far as your script is concerned, was set by -ErrorAction or if it is coming from your session level.

2
  • Why do you need to know that? Commented Jan 20, 2013 at 19:36
  • any final solution with full source code? Commented Mar 21, 2013 at 10:31

3 Answers 3

5

$ErrorActionPreference is a variable in the global(session) scope. If you run a script and don't specify the -ErrorAction parameter, it inherits the value from the global scope ($global:ErrorActionPreference).

If you specify -ErrorAction parameter, the $ErrorActionPreference is changed for your private scope, meaning it's stays the same through the script except while running code where you specified something else(ex. you call another script with another -ErrorAction value). Example to test:

Test.ps1

[CmdletBinding()]
param()

Write-Host "Session: $($global:ErrorActionPreference)"
Write-Host "Script: $($ErrorActionPreference)"

Output:

PS-ADMIN > $ErrorActionPreference
Continue

PS-ADMIN > .\Test.ps1
Session: Continue
Script: Continue

PS-ADMIN > .\Test.ps1 -ErrorAction Ignore
Session: Continue
Script: Ignore

PS-ADMIN > $ErrorActionPreference
Continue

If you wanna test if the script was called with the -ErrorAction paramter, you could use ex.

if ($global:ErrorActionPreference -ne $ErrorActionPreference) { Write-Host "changed" }

If you don't know what scopes is, type this in a powershell console: Get-Help about_scopes

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

Comments

3

Check the $MyInvocation.BoundParameters object. You could use the built-in $PSBoundParameters variable but I found that in some instances it was empty (not directly related to this question), so imo it's safer to use $MyInvocation.

function Test-ErrorAction
{
    param()

    if($MyInvocation.BoundParameters.ContainsKey('ErrorAction'))
    {
        'The ErrorAction parameter has been specified'
    }
    else
    {
        'The ErrorAction parameter was not specified'
    }
}

Test-ErrorAction

Comments

0

If you need to know if the cmdlet was called with the -ErrorAction parameter do like this:

[CmdletBinding()]
param()

if ($myinvocation.Line.ToLower() -match "-erroraction" )
    {
      "yessss"
    }
else
    {
      "nooooo"
    }

This is true alse when the parameter have same value as the global $ErrorActionPreference

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.