我经常使用在脚本范围中声明的变量来避免函数及其范围的问题.我正在声明这样的变量:
New-Variable -Name test -Option AllScope -Value $null
Run Code Online (Sandbox Code Playgroud)
...或者有时我会像这样切换现有的变量来全面使用它们:
$script:test = $test
Run Code Online (Sandbox Code Playgroud)
当我想要清除它们时,我要么使用它:
Clear-Variable test -Scope Script
Run Code Online (Sandbox Code Playgroud)
......或者我只是用这个:
$test = $null
Run Code Online (Sandbox Code Playgroud)
有区别吗?我应该更喜欢什么?为什么?
小智 9
从get-Help:
Clear-Variable cmdlet删除存储在变量中的数据,但不删除变量.结果,变量的值为NULL(空).如果变量具有指定的数据或对象类型,则Clear-Variable会保留变量中存储的对象的类型.
所以Clear-Variable,$var=$null几乎是等价的(保留的输入除外).一个完全相同的是做$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
Run Code Online (Sandbox Code Playgroud)
并回答可能是下一个问题:如何完全删除变量(因为缺少的变量与空值变量不同)?简单地做
rm variable:/p
Test-Path variable:/p => $false
Run Code Online (Sandbox Code Playgroud)
为了补充Marcanpilami 的有用答案:
注意:要完全删除(取消定义)变量,请使用Remove-Variable <name> [-Scope <scope>].
除非 $test用 定义Set-Variable -Option AllScope,
Clear-Variable test -Scope Script和
$test = $null一般而言并不等同。
(对于 Set-Variable -Option AllScope它们来说,但是这个-Scope参数就变得无关紧要了,因为这样在所有范围内只有一个变量实例存在(概念上)。)
$test = $null-除非在与最初创建变量时相同的作用域中执行- 将在当前作用域中隐式创建一个变量(并分配给它),并保持原始变量不变。 有关 PS 中变量作用域的更多信息,请参阅此答案testtest$null
请注意,变量赋值语法也通过作用域前缀提供作用域,但仅限于global, script, 和local(默认):$global:test = $null, $script:test = $null,$local:test = $null
还有作用域private:local它的一种变体可以防止后代作用域看到变量 - 再次,请参阅此答案。
如果您确保目标范围相同,则上面的两种形式在功能上是等效的:它们分配给目标变量。[1]$null
然而,使用 usingClear-Variable可以让你做两件事,但$<scope>:testing = ...不能:
该-Scope参数还接受一个数值,指示相对于当前范围的范围:0是当前范围,1是父范围,等等。
您可以定位多个变量(作为名称数组或使用通配符)
[1]陷阱:
请注意,如果目标变量是类型约束的(使用“强制转换符号”分配;例如, ), 则无论使用或,都会保留[int] $i = 1该类型,并且可能会发生隐式类型转换,这可能会产生意外结果或完全失败:$testing = $nullClear-Variable
[int] $i = 1 # type-constrain $i as an integer
Clear-Variable i # equivalent of $i = $null
$i # !! $i is now 0 (!), because [int] $null yields 0
[datetime] $d = 1 # type-constrain $d as DateTime
Clear-Variable d # !! FAILS, because `$d = $null` fails, given that
# !! $null cannot be converted to [datetime]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15475 次 |
| 最近记录: |