arrayspowershelldynamic-variables

Powershell catch dynamic variable and add to array


I seek assistance in figuring out how to capture new dynamic variables and add them to an array.

Below is a sample code that creates the variables.

foreach ($user in $users) {
    New-Variable -Name "$($user)_pwString"  -Value ([System.Web.Security.Membership]::GeneratePassword(10,4)) -Force
}

This will create several variables as such:
$Guest01_pwString
$Guest02_pwString
$Guest03_pwString

How could capture each of the variables it creates and add them into an array.

What I thought would have worked:

$secureStrings = @()
foreach ($user in $users) {
    $secureStrings += (New-Variable -Name "$($user)_pwString"  -Value ([System.Web.Security.Membership]::GeneratePassword(10,4)) -Force)
}

Solution

  • You need the -PassThru switch in order to pass the newly created variable object through to the output stream, and you can use that object's .Value property to access the variable's value:

    $secureStrings = @()
    foreach ($user in $users) {
      $secureStrings += (New-Variable -PassThru -Name "$($user)_pwString"  -Value ([System.Web.Security.Membership]::GeneratePassword(10,4)) -Force).Value
    }
    

    You can streamline your command as follows:

    [array] $secureStrings = 
      foreach ($user in $users) {
        (Set-Variable -PassThru -Name "${user}_pwString"  -Value ([System.Web.Security.Membership]::GeneratePassword(10, 4))).Value
      }
    

    Taking a step back: Instead of creating individual variables, consider using an (ordered) hashtable:

    $secureStrings = [ordered] @{}
    foreach ($user in $users) {
      $secureStrings[$user] = [System.Web.Security.Membership]::GeneratePassword(10, 4)
    }
    

    You can then use $secureStrings.Values to extract the passwords only.