【问题标题】:remove-variable and pipeline - null-valued expression?删除变量和管道 - 空值表达式?
【发布时间】: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


【解决方案1】:

我最后通过在管道的 where-object 部分添加更多空检查来修复它(感谢@ScottHeath):

get-variable | where-object { $null -ne $_ -And $null -ne $_.Value -And $null -ne $Excel -And $_.Value.ToString() -eq $Excel.GetType().ToString() } | foreach { Remove-Variable -Name $_.Name }

【讨论】:

    【解决方案2】:

    Com 对象需要从内存中释放:

    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    

    之后,用

    删除变量本身
    $Excel = $null
    Remove-Variable -Name Excel
    

    Remove-Variable 还有一个-Include 参数,您可以在其中指定变量名数组。那里也允许使用通配符。

    【讨论】:

    • 谢谢@Theo。你最懂我心。我刚刚读到这个:support.microsoft.com/en-us/help/317109/… 最后提到使用 FinalReleaseComObject 而不是 ReleaseComObject ....
    • @Captain_Planet 我不知道那个,但FinalReleaseComObject 显然可以作为循环ReleaseComObject 的替代品,因为我们不是在这里循环......无论如何,很高兴知道。跨度>
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 2020-04-26
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    相关资源
    最近更新 更多