Why does getting-variable attribute access via Get-Variable only work in ISE for the first time?

Thanks to the great people at StackOverflow, we got a very good answer on how to get the values ​​defined in ValidateSeta sentence of Param()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 you run it in PowerShell ISE. the second time , you run it, there is no way out.

Is there a workaround so that it always works? We use PowerShell 4.0 for Win 7 and Win 2012.

+4
source share
2 answers

TL; DR

  • , , Windows PowerShell v5.1/PowerShell Core v6.0-beta.4 - . GitHub.

  • , :

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

$MyInvocation.MyCommand.Parameters['Type'].Attributes.ValidValues

, Set-StrictMode -version 2 PSv2,

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

($MyInvocation.MyCommand.Parameters['Type'].Attributes |
  Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] }).ValidValues

ISE , - (ISE ).

Dot-sourcing ( , ), , , .
dot-source a script , , , PS.

script $Type , .

, script (, script ./script.ps1:

  • $Type - :

    > . ./script.ps1; (Get-Variable Type).Attributes.Count
    Startup
    Shutdown
    LogOn
    LogOff
    3   # PS implicitly adds 2 add'l attributes behind the scenes
    
  • dot-source, :

    > . ./script.ps1; (Get-Variable Type).Attributes.Count
    0
    
+2

, PowerShell ISE ( ). .

, , :

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

(Get-Variable Type).Attributes.ValidValues

# Do your stuff here

Remove-Variable Type
+3

Source: https://habr.com/ru/post/1671894/


All Articles