I often use variables which are declared in the script scope to avoid problems with functions and their scopes. I am declaring these variables like this:
New-Variable -Name test -Option AllScope -Value $null
... or sometimes I switch existing variables like this to use them comprehensively:
$script:test = $test
When I want to clear them I either use this:
Clear-Variable test -Scope Script
... or I simply use this:
$test = $null
Is there a difference? What should I prefer and why?
From the get-Help:
The Clear-Variable cmdlet deletes the data stored in a variable, but it does not delete the variable. As a result, the value of the variable is NULL (empty). If the variable has a specified data or object type, Clear-Variable preserves the type of the object stored in the variable.
So Clear-Variable
and $var=$null
are nearly equivalents (with the exception of the typing which is retained). An exact equivalent would be to do $var=[mytype]$null
.
You can test it yourself:
$p = "rrrr"
Test-Path variable:/p # => $true
$p = $null
Get-Member -InputObject $p # => error
$p = [string]$null
Get-Member -InputObject $p # => it is a string
And to answer what may be the next question: how to completely remove a variable (since an absent variable is different from a null-valued variable)? Simply do
rm variable:/p
Test-Path variable:/p => $false