1

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)
}

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So I just tried your code for the hashtable, however how do I extract only the name field. Also for any of these the array doesn't show the values as a variable. I'll need to pass each variable to ConvertTo-SecureString -AsPlainText -Force. I was trying to keep the values separate so I can convert the password to a secure string then extract the value to be placed into a CVS file.
Never mind on extracting the name, I had tried $SecureStrings.name earlier and returned no output, however second time round that worked. Just need to figure out how I would pass this through a loop to convert each variable into a secure string.
@Run.Bat, to get the names (keys) stored in the hashtable, use $secureStrings.Keys. You can enumerate the hashtable entries (key-value pairs) with $secureStrings.GetEnumerator()
@Run.Bat, as for the array: I had assumed you only wanted to store the passwords themselves, not the whole variable objects, but if you wan the latter, simply omit the (...).Value around the New-Variable / Set-Variable call.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.