Clear-Variable

PowerShell Cmdlet Deep Dive: Clear-Variable

Welcome back to Wahman’s PowerShell Blog! Today we’re exploring a useful cmdlet that helps keep your scripting environment clean and organized. Let’s talk about Clear-Variable.

What does Clear-Variable do?

According to Microsoft, Clear-Variable “Deletes the value of a variable.” In simple terms, this cmdlet clears out the contents of a variable without removing the variable itself. This can be handy when you want to reuse a variable or clean up memory usage in long scripts.

Syntax

Clear-Variable [-Name] <String[]> [-Scope <String>] [-Force] [-WhatIf] [-Confirm]

Let’s look at some examples

Example 1: Basic Use – Clear a Variable

$myVar = "Hello, World!"
Clear-Variable -Name "myVar"
$myVar  # Output will be empty

This is a basic use case. We assign a string to $myVar, clear it, and if we echo it again, we’ll see it no longer contains any data. Note: $myVar still exists, it’s just $null.

Example 2: Clear Multiple Variables

$a = 5
$b = 10
$c = 15
Clear-Variable -Name a,b,c
$a  # Output: blank
$b  # Output: blank
$c  # Output: blank

You can pass multiple variable names to the -Name parameter to clear several variables at once. Very useful for cleaning up after a script has done its job.

Example 3: Use with Different Scopes

function Test-Scope {
    $scopedVar = "I'm in a function"
    Clear-Variable -Name scopedVar -Scope Local
    "scopedVar after clear: $scopedVar"
}
Test-Scope

This demonstrates clearing variables in a local scope, such as inside a function. The -Scope parameter is powerful when dealing with advanced scripts that span multiple scopes.

Example 4: Use in Advanced Scripts with -Force

Set-Variable -Name "readonlyVar" -Value 123 -Option ReadOnly
Clear-Variable -Name "readonlyVar" -Force
$readonlyVar  # Output: blank

Normally, you can’t clear a ReadOnly variable — unless you use the -Force parameter. Just be cautious: using -Force can bypass some protections in your scripts.

When should you use Clear-Variable?

  • To release memory in long-running scripts
  • To prevent stale data from affecting logic in loops or functions
  • As part of a script cleanup routine before exiting your scripts

That’s a wrap on today’s cmdlet spotlight! Now you know how to make the most of Clear-Variable in your PowerShell scripts, from simple usage to more advanced scenarios involving scope and force.

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 *