April 2nd, 2009

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]

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.