Many² ways you can set a variable value

Many² ways you can set a variable value

  • Comments 4

There are many ways to set a variable's value.

I just learnt one more yesterday. If you have others, please add comments

# Simple
# $ gets the variable, and = will assign it
$a = 1

# With Variable Scope
# The prepend is the scope, and could be global, script, and others
# Useful when you want to keep things in script scope, or share them out in global scope
$global:a = 1

# Complex variable names
# Useful if you have a variable with the name ${Yahoo!Id}
${a} = 1

# Using the Set-Variable cmdlet
# Useful if you want to indirectly set the value
# Has extra parameters like scope
Set-Variable a 1

# Using the variable provider
# Never useful, just cool
set-item variable:\a 1

# Using the variable provider with provider shortcut
# Useful when you want to do ${env:ProgramFiles(x86)}
${variable:a} = 1

# Using the SessionState (PowerShell APIs)
# Useful when you dont want to access the Runspace Directly
# Useful when you want to set tied variable
# http://blogs.msdn.com/powershell/archive/2009/03/26/tied-variables-in-powershell.aspx
$executioncontext.SessionState.PSVariable.Set('a', 1)

# Using references
# Useful if you want to indirectly set the value
$ref = [ref]$a
$ref.Value = 10

Have fun,
Ibrahim Abdul Rahim [MSFT]

Leave a Comment
  • Please add 2 and 2 and type the answer here:
  • Post
  • I do the following in a script:

    $foo = 1

    powershell{

    $bar = $foo * 2

    [Environment]::SetEnvironmentVariable("Bar", "2", "User")

    }

    Write-Host $env:Bar

    Could I use $global:bar = $foo * 2

    If I don't use something unusal the variable doesn't persist whe the sub-instance of powershell is closed.

  • What would the last one with [ref] be used for?

  • You can also set a variable using -outvariable

    1 | select -outvariable blah > $null

    $blah

    Another way of using the provider is setting the value with Set-Content

    2 | set-content variable:blah

  • What can I do if i want to give a variable to a cmd from a PS so that I can refer in the cmd via %VAR% to the PS variable?

    if I set the Variable like this it does not work =(

    $global:VAR="C:\anyPath"

Page 1 of 1 (4 items)