Clear-Variable 和将变量设置为 NULL 的区别 [英] Difference between Clear-Variable and setting variable to NULL

查看:65
本文介绍了Clear-Variable 和将变量设置为 NULL 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用在脚本作用域中声明的变量来避免函数及其作用域的问题.我像这样声明这些变量:

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?

推荐答案

来自 get-Help:

From the get-Help:

Clear-Variable cmdlet 会删除存储在变量中的数据,但不会删除该变量.因此,变量的值为NULL(空).如果变量具有指定的数据或对象类型,则 Clear-Variable保留存储在变量中的对象的类型.

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.

所以 Clear-Variable$var=$null 几乎是等价的(保留的类型除外).完全等效的是执行 $var=[mytype]$null.

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.

你可以自己测试:

$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

这篇关于Clear-Variable 和将变量设置为 NULL 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆