Reputation: 1
So, I have an interesting problem that I'm having no luck solving. I have a need to create a bunch of dynamic array variables.
code:
$temp = 'arr1=(1,2,3);arr2=(4,5,6);arr3=(7,8,9)'
foreach($item in $temp.split(";")){
$var = $item.split("=")
New-variable $var[0] $var[1]
get-variable $var[0]
}
Results:
$arr1 (1,2,3)
... (4,5,6)
... (7,8,9)
I have variable $temp which contains a semicolon delimited list of variables/values I want to create. As you can see above I am using new-variable to create this. What is interesting is when I run this from a script, new-variable works for the first call but then I get "..." for all other variables in the array. Any idea what might be causing this?
Upvotes: 0
Views: 233
Reputation: 1
Not sure why this was happening but when I was splitting my string I was getting some random ascii character in my array. Able to see this thanks to PowerGUI!!! The solution was to trim the string prior to using it. (i.e. $var[0].Trim() )
Upvotes: 0
Reputation: 354406
As Andy already pointed out in a comment, you're not creating a semicolon-separated list, you're creating several variables named $arr1
, $arr2
, etc. and $temp
just refers to $arr1
.
A way of fixing your code would be
$temp = 'arr1=(1,2,3);arr2=(4,5,6);...'
Note that for New-Variable
you cannot prefix the $
sigil. The variable name is arr1
, even if you refer to it in code as $arr1
or (gv arr1).Value
or whatever.
But that's a really strange way to write code in PowerShell. You just don't really provide enough detail so that we would actually know what you're doing.
You can just as well do
$arr1 = '(1,2,3)'
$arr2 = '(4,5,6)'
...
Upvotes: 2