1

So I got this code :

$t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10, $t11 = $list[0].split(" ")

but is too much, and I think I can automate the creation of $t variables. How is the correct procedure? with loop but to have the same result.

for ($i=0;$i -le 21; $i++) {
    $objResult += New-Object -TypeName PSObject -Property @{"C$i" = ($list[0].split(" "))[$i]} 
}

or with

set-variable -name "T$i" -value ($list[0].split(" "))[$i]
1
  • 4
    Honestly? Use an array here. If your variable names are really $t1, $t2, etc. there is nothing interesting being learned from the names (as opposed to $id, $name, etc.) and you could just as well use an array. Commented Nov 26, 2013 at 8:23

1 Answer 1

1

If these are simple variables, Set-Variable works perfectly. like so:

for ($i = 0; $i -lt 3; $i++) {
set-variable -name "test$i" -value $i
}

$test0
$test1
$test2

PS > .\test.ps1
0
1
2

If you are looking to work with somewhat more complicated variables (such as COM objects for instance) then New-Object is what you need.

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

1 Comment

yes I wil prefer object but: for ($i = 0; $i -lt 22; $i++) { $objResult += New-Object -TypeName PSObject -Property @{ "test$i" = ($list[0].split(" "))[$i] } } I got: only the last property:test22, it doesn't save them all. TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- ..... test0 NoteProperty System.String test0=1384630490

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.