Clear-Variable

PowerShell Cmdlet Deep Dive: Clear-Variable

Welcome back to Wahmans PowerShell blog! Today we’re covering a fundamental cmdlet that’s incredibly useful in both scripting and interactive sessions: Clear-Variable.

According to Microsoft Docs, the Clear-Variable cmdlet “deletes the value of a variable.” That means it doesn’t remove the variable itself, but it sets its value to $null. This can be helpful for resetting state or sanitizing data between operations without actually removing the variable declaration itself.

Basic Syntax

Clear-Variable -Name <String[]>

You can also use various parameters like -Scope and -Force for advanced use cases. But let’s look through some practical examples from beginner to more advanced usage.

Example 1: Beginner – Clearing a Simple Variable

$name = "John Doe"
Write-Host "Before: $name"
Clear-Variable -Name "name"
Write-Host "After: $name"  # This will output 'After: '

This example demonstrates clearing a simple string variable. After using Clear-Variable, the variable $name becomes $null.

Example 2: Intermediate – Using Clear-Variable in a Function

function Reset-Counter {
    $global:counter = 42
    Write-Host "Counter before clear: $global:counter"
    Clear-Variable -Name "counter" -Scope Global
    Write-Host "Counter after clear: $global:counter"
}

Reset-Counter

In this example, we define a global variable $counter and then clear it using -Scope Global to ensure the correct scope is targeted.

Example 3: Advanced – Clearing Multiple Variables

$var1 = "One"
$var2 = "Two"
$var3 = "Three"
Write-Host "Before: $var1, $var2, $var3"
Clear-Variable -Name var1,var2,var3
Write-Host "After: $var1, $var2, $var3"  # Outputs: 'After:    '

This is a handy way to clear multiple variables at once. This keeps your scripts clean and reduces memory usage when you’re done with those variables.

Example 4: Expert – Clear Variables in a Different Scope

function Test-Scope {
    $script:data = "Important Info"
    Write-Host "Before clear in script scope: $script:data"
    Clear-Variable -Name "data" -Scope Script
    Write-Host "After clear in script scope: $script:data"  # Outputs null

In this advanced example, we use -Scope Script to specifically clear a variable defined in script scope. This is particularly useful in modules or larger scripts to maintain good state hygiene.

Summary

Clear-Variable is a straightforward yet powerful cmdlet. It allows you to reset variable values without deallocating them, which can be very useful in long-running scripts, functions, or stateful automation scenarios.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *