Stan
Stan

Reputation: 63

Use a variable returned by Get-Variable

Hopefully this answer isn't above me. I've created a custom object with properties and methods. I create several of them on the fly, depending on what the user selects at the beginning.

So for this example, the script might create $PRD1, $PRD2, $TST1 and $TST4.

$PRD1, $PRD2, $TST1 and $TST4 will have some properties like DebugMode, DisableAppsStartTime, DisableAppsStopTime. They'll have some methods like DisableApps(), EnableApps().

How can I find out which variables the script ended up creating? I can use Get-Variable to know the ones it created (plus I DO still have the initial list of names to create). My issue is that I'm having trouble figuring out to call the ones I've created, in a manner that allows me to use the methods and properties, without a ridiculous mash up of nested foreach/if/switch commands.

I certainly hope that made sense.

Thanks in advance, SS

Upvotes: 2

Views: 331

Answers (2)

mklement0
mklement0

Reputation: 438133

I DO still have the initial list of names to create

Assuming that $list contains this list, the following creates an (ordered) hash table of those variables that were actually created from that list:

$variableMap = [ordered] @{}
(Get-Variable -ErrorAction Ignore -Scope Local $list).
  ForEach({ $variableMap[$_.Name] = $_.Value })

Note: -Scope Local limits the lookup to the current scope[1]; omit it to target all variables visible in the current scope, which includes those from ancestral (parent) scopes.

You can then loop over $variableMap.Keys to process them all, or access one by name selectively, e.g., $variableMap.PRD1 (or $variableMap['PRD1']).

You then use regular dot notation to access properties and methods of these entries; e.g., $variableMap.PRD1.DisableApps().


[1] This includes variables created with the AllScope option, e.g., $HOME, because they are copied to every scope, as the name suggests. You can find all such variables with
Get-Variable | Where-Object Options -match 'AllScope'

Upvotes: 2

shadow2020
shadow2020

Reputation: 1351

I just did this with the where-object cmdlet and the -like operator with an foreach loop.

foreach($var in (get-variable | Where-object {$_.name -like '*PRD*' -or $_.name -like '*TST*'})){
    $var
}

Upvotes: 0

Related Questions