Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear out powershell terminal variables

Tags:

powershell

Say I have the following powershell script:

$hello = "Hello World"
Write-Output $hello

When I run it I get

Hello World

Then I decide that I want my variable to be named $helloWorld:

$helloWorld = "Hello World"
Write-Output $hello

When I run that I get

Hello World

What I want is for that to fail because I have not defined $hello (or at least write out an empty string).

I have seen some examples that try to record off all the variables before running and calling Remove-Variable on all the new ones after. This seems like a lot of work.

I thought I would ask if today's powershell has a better solution. Basically I am looking for a command that will reset the terminal's variable memory back to the initial startup state.

like image 281
Vaccano Avatar asked Apr 27 '26 19:04

Vaccano


1 Answers

If you call Set-StrictMode with -Version 1 or higher, references to nonexistent variables cause an error, both in the current scope and its descendants:

Set-StrictMode -Version 1

$helloWorld = "Hello World"

# Causes a statement-terminating error, because $hello isn't defined.
Write-Output $hello             

Caveats:

  • The error is only a statement-terminating error, which means that script execution will continue by default.

  • If $hello happens to be defined in an ancestral scope, no error will be reported, due to PowerShell's dynamic scoping.

  • IDE caveats:

    • Unfortunately, the obsolescent, Windows PowerShell-only Windows PowerShell ISE invariably runs scripts dot-sourced, i.e. directly in a session's global scope rather than in a child scope, so that previous invocations can leave behind state that affect subsequent ones.

      • Applied to your example: if you initially defined $hello, ran the script, and then changed the variable to $helloWorld, running the script will still succeed even with a strict mode in effect, because the $hello variable is still around.
    • Using Visual Studio Code with the PowerShell extension unfortunately does that too by default, but you can configure it use a new, temporary session for each invocation - see this answer.

like image 102
mklement0 Avatar answered Apr 29 '26 12:04

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!