首页 > 解决方案 > 无法在 Powershell 中删除变量

问题描述

在编写脚本时,我遇到了让我发疯的最奇怪的行为。有时不可能在 Powershell 中删除变量的值。我努力了:

Remove-Variable -Force

还尝试使其等于空字符串或使其等于空字符串,$null但变量值和类型仍然存在。

任何人都知道这是怎么发生的?

我在 Windows Server 2016 上使用 Powershell 版本 5。

这里有一些截图:

无效的 删除变量

标签: powershellvariables

解决方案


要删除变量,请将其名称 不带$符号传递给Remove-Variablecmdlet 的
-Name参数
(位置隐含);使用变量的示例$date

  • 使用参数
# Note the required absence of $ in the name; quoting the var. name is
# optional in this case.
Remove-Variable -Force -Name date
  • 使用管道将要求您指定其属性包含要删除的变量名称的对象.Name,因为这些属性值隐式绑定到Remove-Variable-Name参数;实现这一目标的最简单方法是使用Get-Variablecmdlet,它也需要指定不带$:的名称
# Works, but is inefficient.
Get-Variable -Name date | Remove-Variable -Force

但是,这比直接将名称作为参数传递更冗长且效率更低。


至于你尝试了什么:

您的变量删除命令在概念上存在缺陷:

$date | Remove-Variable -Force

除了赋值( $date = ...) 的 LHS 之外,引用带有$sigil 的变量返回它的,而不是变量本身

也就是说,由于您的$date变量包含一个[datetime]实例,因此通过管道发送的是该实例,并且由于仅支持字符串作为输入 - 即变量名称- 命令失败。

实际上,您的调用等效于以下内容,可以预见的是失败:

PS> Get-Date | Remove-Variable -Force
Remove-Variable : The input object cannot be bound to any parameters for the command 
either because the command does not take pipeline input 
or the input and its properties do not match any of the parameters that take pipeline input.

在这种情况下,有些冗长的一般错误消息暗示的是输入对象的类型错误(因为只.Name接受具有属性的对象,而[datetime]没有)。


您需要引用变量本身而不是其值的上下文:

这些上下文的共同点是您需要指定不带$sigil的变量名。

两个值得注意的例子:

  • 所有*-Variablecmdlet 都需要操作变量的名称,例如Get-Variable返回表示变量的对象的 cmdlet ,类型为System.Management.Automation.PSVariable; 这些对象包括 PowerShell 变量的名称、值和其他属性。

    # Gets an object describing variable $date
    $varObject = Get-Variable date  # -Name parameter implied
    
  • 当您将输出变量的名称传递给-*Variable 公共参数时

    # Prints Get-Date's output while also capturing the output 
    # in variable $date.
    Get-Date -OutVariable date
    

正如上面所暗示的那样,唯一的例外是分配给变量:在那里你确实使用了sigil=$,例如$date = Get-Date

请注意,这与 POSIX 兼容的 shell 不同,例如bash,您不在分配中使用$(并且不能在 周围有空格=);例如,date=$(date)


推荐阅读