Home > Enterprise >  How to use string as variable in powershell
How to use string as variable in powershell

Time:06-29

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

CodePudding user response:

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.

  • Related