2

I have a XAML gui in my powershell script. I would like to know how I can use a string as a variable name ex. $grid.Name is WPFgrdCopy

This works:

$WPFgrdCopy.Background = "#FF212123"

This does not:

$grids = Get-Variable "wpfgrd*"
foreach($grid in $grids){
    $grid.Background = "#FF212123"
}

It doesn't because $grid is an object of the variable, how can I set attributes of $grid.Name (WPFgrdCopy) I have also tried Add-Member -InputObject $grid -NotePropertyMembers @{Background="#FF212123"} -Force

Adam
  • 23
  • 4
  • 3
    `Get-Variable ... -ValueOnly` – Mathias R. Jessen Jun 28 '22 at 15:55
  • 3
    It is generally a bad practice to use the [`-Variable` cmdlets](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/set-variable) for dynamic variable names! Use a [hashtable](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_hash_tables) instead, see also: [How do I automaticaly create and use variable names?](https://stackoverflow.com/a/68830451/1701026) – iRon Jun 28 '22 at 16:36

1 Answers1

4

The objects of type System.Management.Automation.PSVariable that Get-Variable returns have a read-write .Value property.

Therefore, one option is to access $grid.Value rather than $grid:

$grids = Get-Variable "wpfgrd*"
foreach($grid in $grids){
  $grid.Value.Background = "#FF212123"
}

However, as Mathias R. Jessen points out, you can use Get-Variable's -ValueOnly switch to directly return only the matching variables' values, which is sufficient here, given that your intent isn't to modify what object is stored in each variable but merely to modify a property of the current object:

$grids = Get-Variable "wpfgrd*" -ValueOnly
foreach($grid in $grids){
  $grid.Background = "#FF212123"
}

Taking a step back: As iRon points out, if you control the creation of the variables of interest, it may be better to use the entries of a hasthable instead of individual variables - see this answer for more information.

mklement0
  • 382,024
  • 64
  • 607
  • 775