0

I created 4 objects, where Context = "App_Name" And I'm trying to create a variable, and then use it, but I don't know beforehand which name this variable will have, because it depends on which object is used right now.

With what I have below, I can list the name of the variable, but my question is how to call one of them, the one of the on-going object.

Like if object context is "paint", calling $list_of_paint without knowing this name.

Something like $$VarName (which doesn't work, but so you can see the logic)

[System.Collections.ArrayList]$ndf = @()
$test = "2"
$VarName = "list_of_" + $obj.context
New-variable -Name $VarName -value "$test" -Force | ForEach-Object $ndf.add("$" + "$VarName)
Dasheng
  • 1
  • 1
  • Does this answer your question? [Dynamically create variables in PowerShell](https://stackoverflow.com/questions/13015303/dynamically-create-variables-in-powershell) – Jesse Nov 04 '22 at 16:49
  • Using `New-Variable` in this case is bad practice. Prefer to use a [`hashtable`](https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable?view=powershell-7.2) instead. This keeps the related information in one place, instead of cluttering the variable name space. – zett42 Nov 04 '22 at 17:04
  • 1
    See: [How do I automaticaly create and use variable names?](https://stackoverflow.com/a/68830451/1701026) – iRon Nov 04 '22 at 17:36

1 Answers1

0

The way I work around this was to creator another property to my object.

[PSTypeName ("Obj1")]$Object1 = [PSCustomObject]@{
  PSTypeName = "SpecObject"
  context = "contextobject"
  varname = "list_of_contextobject"
  $ObjArray = @($Object1, $Object2, $Object3)
  $test = "2"
  foreach ($obj in $ObjArray) {
    New-variable -Name $obj.varname -value "$test" -Force
  }
}

That way I can call the good one anytime by using the $obj.varname within my foreach.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Dasheng
  • 1
  • 1