PowerShell Cmdlet Deep Dive: New-Variable
Welcome back to Wahmans PowerShell blog! Today, we’re going to explore the New-Variable cmdlet. This useful command allows us to create new variables in PowerShell scripts and sessions. Whether you’re new to scripting or an experienced scripter looking to tighten your variable management, this cmdlet has something for you.
What is New-Variable?
According to Microsoft, New-Variable “creates a new variable.” That might sound simple, but there’s a lot of power under the hood. You can define the scope, set variable options, or even add read-only protections.
Basic Syntax
New-Variable -Name <String> -Value <Object>
At its most basic, that’s all you need to know. But let’s walk through four practical examples—from beginner to more advanced use cases.
Example 1: Simple Variable Creation
This is the most basic usage of New-Variable. Think of it as the equivalent of doing $myVar = "Hello World".
New-Variable -Name myVar -Value "Hello World"
Write-Output $myVar
Output: Hello World
Example 2: Creating a Read-Only Variable
Sometimes you want to prevent a variable from being accidentally overwritten. That’s where -Option ReadOnly comes in handy.
New-Variable -Name configPath -Value "C:\App\config.json" -Option ReadOnly
# Try to change the value (this will throw an error)
$configPath = "C:\Other\config.json"
This is especially useful in production scripts where certain values must remain immutable.
Example 3: Using -Scope to Define Variable Lifetime
You can use the -Scope parameter to limit where the variable is accessible (Global, Local, Script).
function Test-Scope {
New-Variable -Name localVar -Value "Only Here" -Scope Local
Write-Output $localVar
}
Test-Scope
# This will error out because localVar is not available in the global scope
Write-Output $localVar
Use scope to keep your variables clean and avoid accidental name collisions.
Example 4: Dynamically Creating Variables from a List
In more dynamic scripts, you might want to build variable names on the fly. Here’s how you can do that using a loop.
$names = @("server1", "server2", "server3")
foreach ($name in $names) {
New-Variable -Name $name -Value "10.0.0.$($names.IndexOf($name) + 1)"
}
# Access the variables
Write-Output $server1 # Output: 10.0.0.1
Write-Output $server2 # Output: 10.0.0.2
Write-Output $server3 # Output: 10.0.0.3
This is a powerful way to deal with dynamic environments or configuration lists.
Wrap-up
The New-Variable cmdlet is more than just an alternative way to assign variables—it’s a tool for building robust, safe, and dynamic scripts. From setting read-only variables to scoping and automating variable creation, this cmdlet belongs in every PowerShell user’s toolkit.
Happy scripting, and I will see you in the next post!
Leave a Reply