Powershell: Checking if a script was called with -ErrorAction?

Scripts (with CmdletBinding) and cmdlets have a standard -ErrorAction parameter available when called. Is there a way, within the script, if you actually called the script with -ErrorAction?

The reason I am asking is that I want to know if the automatic value of the variable for $ ErrorActionPreference with respect to your script was set by -ErrorAction or if it comes from your session level.

+3


source to share


3 answers


$ErrorActionPreference

is a variable in the global (session) scope. If you run the script and don't specify a parameter -ErrorAction

, it inherits the value from the global scope ( $global:ErrorActionPreference

).

If you specify a parameter -ErrorAction

, it $ErrorActionPreference

will be changed for your personal scope, that is, it will remain the same with the script, except that you specified something else when you run the code (for example, you call another script with a different value -ErrorAction

). Example for testing:

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 want to check if the script was called with a parameter -ErrorAction

, you can use ex.

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

      

If you don't know what the scopes are, enter this in the powershell console: Get-Help about_scopes

+4


source


Check the $ MyInvocation.BoundParameters object. You can use the built-in $ PSBoundParameters variable, but I found it was empty in some cases (not directly related to this question), so 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

      

+3


source


If you need to know if a cmdlet was called with a parameter -ErrorAction

, follow these steps:

[CmdletBinding()]
param()

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

      

It is true

alse when the parameter has the same value as the global$ErrorActionPreference

0


source







All Articles