powershell - 无法在 Powershell 中删除变量
问题描述
在编写脚本时,我遇到了让我发疯的最奇怪的行为。有时不可能在 Powershell 中删除变量的值。我努力了:
Remove-Variable -Force
还尝试使其等于空字符串或使其等于空字符串,$null
但变量值和类型仍然存在。
任何人都知道这是怎么发生的?
我在 Windows Server 2016 上使用 Powershell 版本 5。
这里有一些截图:
解决方案
要删除变量,请将其名称 不带$
符号传递给Remove-Variable
cmdlet 的
-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-Variable
cmdlet,它也需要指定不带$
:的名称
# 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的变量名。
两个值得注意的例子:
所有
*-Variable
cmdlet 都需要操作变量的名称,例如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)
。
推荐阅读
- java - 无法将 Gradle 构建为 Make 项目
- vba - 修改 PowerPoint 中嵌入图表的范围
- android - 如何在Adapter中设置RelativeLayout的可见性和setText
- angular - Angular main-client.js 请求因 net::ERR_SPDY_PROTOCOL_ERR 失败
- masstransit - 使用 MassTransit 发布活动
- amazon-web-services - 找不到配置文件,makefile 中出现错误 255
- python - 如何抓取下一行 HTML
- google-sheets - 如何检查查询参数是否为空?
- javascript - 使用 Angular 和 Java 之间的 Web 套接字发送和接收数据(比如文本)
- java - 替换事务后重用带有嵌套片段的片段