powershellreflectionpowershell-ise

Why does accessing a parameter variable's attributes with Get-Variable only work the first time in the ISE?


Thanks to the great people at StackOverflow we received a very good answer on how to retrieve the values defined in ValidateSet within the Param() clause of a script or function:

Param (
    [ValidateSet('Startup', 'Shutdown', 'LogOn', 'LogOff')]
    [String]$Type = 'Startup'
)

(Get-Variable Type).Attributes.ValidValues

The only thing that bothers me is that this code only works the first time when you run it in the PowerShell ISE. The second time you run it, there is no output generated.

Is there a workaround to have it always working? We use PowerShell 4.0 on Win 7 and Win 2012.


Solution

  • tl;dr

    Param (
        [ValidateSet('Startup', 'Shutdown', 'LogOn', 'LogOff')]
        [String] $Type = 'Startup'
    )
    
    $MyInvocation.MyCommand.Parameters['Type'].Attributes.ValidValues
    

    If there's a chance that Set-StrictMode -version 2 or higher is in effect or you're using PSv2, use

    Param (
        [ValidateSet('Startup', 'Shutdown', 'LogOn', 'LogOff')]
        [String] $Type = 'Startup'
    )
    
    ($MyInvocation.MyCommand.Parameters['Type'].Attributes |
      Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] }).ValidValues
    

    Optional background information

    The problem is not related to the ISE per se, but to repeated dot-sourcing (the ISE just happens to run all scripts by dot-sourcing them).

    Dot-sourcing runs scripts in the current scope (in the caller's scope itself, as opposed to in a child scope) and therefore typically modifies the current scope's state, such as by adding variables.
    If you dot-source a script from an interactive session, you're effectively modifying the global session state, which is how definitions from the PS profile files are loaded, for instance.

    In the case at hand, a dot-sourced invocation of the script effectively adds parameter variable $Type to the invoking scope as a regular variable, as designed.

    The bug surfaces when you dot-source the same script again (assume that the script in the question is present as ./script.ps1: