【发布时间】:2019-10-30 10:43:42
【问题描述】:
我正在尝试删除我的 PowerShell 脚本中的一些变量,如下所示:
#create example com object
$Excel = New-Object -ComObject Excel.Application
#do something with COM object, close COM object etc
#clear variable
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | remove-variable
但它返回: 您不能在空值表达式上调用方法。
在 get-variable.... 行?但是,当我像这样测试该行时:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | Select -Property Name
它返回正确的数据?我得到相同的行为:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | ForEach-Object { remove-variable -Name $_.Name }
我不明白为什么 remove-variable 不起作用? remove-variable cmdlet 通过“PropertyName”在管道中接受“Name”,所以我认为这对我来说还可以吗?
更新
有趣的是,完整的错误是多次出现(有趣,因为该行应该只返回 3 个结果,但有 48 个这样的错误消息):
You cannot call a method on a null-valued expression.
At line:3 char:31
+ ... re-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.Ge ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
也
这行得通:
$vars = get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | Select-object -ExpandProperty Name
foreach ($var in $vars) {
remove-variable -Name $var
}
但这不是?:
get-variable | where-object { $_.Value -ne $null -And $_.Value.ToString() -eq $Excel.GetType() } | foreach { remove-variable -Name $_.Name }
【问题讨论】:
-
请发布完整的错误:)
-
$null 应该总是在操作符的左边
标签: powershell