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.
CodePudding user response:
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.
- Applied to your example: if you initially defined
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.
CodePudding user response:
I am not quite sure of the exact situation of this, however here are some approaches I would use:
powershell
- create a new instance of powershellRemove-Variable * -ErrorAction SilentlyContinue
- see here