1

How can I declare variables and assign values to them at run time.

Reason: I am fetching these variables values from sql server and these variable values are configurable in nature

Code which I have tried till now

   [array]$varArray = @($($ServerName),$($HostName)) 

 foreach($varname in $varArray)
        {
          $varname = "some test value"
        }

Write-Host $ServerName
Write-Host $HostName
1
  • @Ansgar Yeah ! I did figure it out and at the same time I removed the edited part. Thanks a lot for your assistance. :D Commented Mar 27, 2013 at 9:52

2 Answers 2

7

The simplest way of using dynamically named variables would be a dictionary:

$vars = @{}  # create empty dictionary

# add key/value pairs to dictionary:
$vars["foo"] = 23
$vars["bar"] = "foobar"
$vars["baz"] = Get-Content C:\sample.txt

Another way would be to declare variables on the fly:

$name  = "foo"
$value = "bar"

New-Variable $name $value

echo $foo

Or you could create a custom object and add properties as Kyle C suggested. That approach is similar to a dictionary, although technically different.

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

1 Comment

Note that for the second method you can also use Get-Variable -Name $name -ValueOnly. You never actually need to know the name of the dynamic variable.
2

You could try adding a NoteProperty to the object.

$varname | Add-Member -type NoteProperty -name TestProperty -value "some test value" -PassThru

Also see this for what types of objects you can add a member to: What objects are suitable for Add-Member?

6 Comments

I have tried replacing $varname = "some text value" with $varname | Add-Member -type NoteProperty -name $varname -value "some test value" but it didn't work. I am quite sure I have missed the context of your answer, can you assist me as I am completely new to powershell. (started 5 hours back)
Do you have a little more information about the object type you are getting back? can you do $varname | Format-List ?
All those variables which is defined in array (ex:servername, hostname.. etc) are of string type only.
with this code [array]$varArray = @($($ServerName),$($HostName)) foreach($varname in $varArray) { $varname = "some test value" Write-Host $varname | Format-List } I am getting some test value some test value
you don't want to assign $varname - can you try $varname.GetType().FullName without assigning anything to it?
|

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.