header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
use 1 variable to define the name of another variable
Last Post 10 Sep 2010 01:02 PM by Shay Levy. 5 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
thanosazlinUser is Offline
New Member
New Member
Posts:19
Avatar

--
09 Sep 2010 10:01 AM
    new to powershell still learning. just wondering how would i take a variable and use it to define the name of another variable.

    example:
    $a = 1

    $test"$a" = "testing code"

    so that i would have a variable called $test1 that would contain "testing code"???

    i also tried $test'$a'  not able to google the right keywords to find anything to help me out :) .
    Shay LevyUser is Offline
    PowerShell MVP, Admin
    Veteran Member
    Veteran Member
    Posts:1362
    Avatar

    --
    09 Sep 2010 01:06 PM
    When you embed a variable in a string powershell expand it and you get the value (not the name). Try this:

    new-variable -name ("test"+(get-variable a).name) -value "testing code"

    Shay Levy
    Windows PowerShell MVP
    http://PowerShay.com
    PowerShell Community Toolbar
    Twitter: @ShayLevy
    thanosazlinUser is Offline
    New Member
    New Member
    Posts:19
    Avatar

    --
    10 Sep 2010 07:10 AM
    thanks for that, you posts are always helpful :).. i couldn't get it work, it was creating a var named $testa instead of $test1 which the 1 is the value of a, so i tried the below code and it worked using -valueonly

    $a = 1

    new-variable -name ("test"+(get-variable a -valueonly)) -Value "testing code"

    $test1
    Shay LevyUser is Offline
    PowerShell MVP, Admin
    Veteran Member
    Veteran Member
    Posts:1362
    Avatar

    --
    10 Sep 2010 12:45 PM
    Cool, I though you wanted the variable name :)

    Shay Levy
    Windows PowerShell MVP
    http://PowerShay.com
    PowerShell Community Toolbar
    Twitter: @ShayLevy
    cameronoveUser is Offline
    Basic Member
    Basic Member
    Posts:332
    Avatar

    --
    10 Sep 2010 12:55 PM
    New-Variable -name "test$a" -Value "Testing Code"
    Shay LevyUser is Offline
    PowerShell MVP, Admin
    Veteran Member
    Veteran Member
    Posts:1362
    Avatar

    --
    10 Sep 2010 01:02 PM
    Exactly! :)

    Shay Levy
    Windows PowerShell MVP
    http://PowerShay.com
    PowerShell Community Toolbar
    Twitter: @ShayLevy
    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer