Powershell catch dynamic variable and add to array
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.