Many² ways you can set a variable value

PowerShell Team

PowerShell Team

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]

PowerShell Team
PowerShell Team

Follow PowerShell Team   

No Comments.