我想知道这是否可以删除当前脚本 session 中使用的所有变量?

Try {
    Write-Host "Scripting start...."
}
Catch {
    Write-Warning -Message "[PROCESS] Something wrong happened"
    Write-Warning -Message $Error[0].Exception.Message
}
Finally {
    Remove-Variable *
    [System.GC]::Collect()
}
如果没有,我可以在 Finally 块中做什么?

最佳答案

最好的做法是使用一些熵来命名您的自定义变量,以便轻松找到和删除它们。删除 '*' 会删除所有内容,无论它是何时/如何创建的,包括所有 PS 默认变量。
不要这样做。
在每次 session 运行时,将默认值和自动值收集在一个变量中,在您结束 session 之前,将该变量集合与您创建的进行比较,并仅删除您创建的内容。
所以,就我而言,我会使用,说......

$panVariableName
... 然后
Remove-Variable -Name 'pan*' -Force
或者,如果您不想这样做。在 session 开始时,执行此操作...
$AutomaticVariables = Get-Variable
...然后您可以比较您创建的任何变量,无论您如何命名它们以获取您的删除集合。这是我在模块配置文件中保留的一个函数,用于与这种方法相关的清理用例。
所以,在我的模块配置文件中,这是在顶部......
$AutomaticVariables = Get-Variable
然后当我准备好时调用这个函数。
Function Clear-ResourceEnvironment
{
    [CmdletBinding(SupportsShouldProcess)]
    [Alias('cre')]

    Param
    (
        [switch]$AdminCredStore
    )


    [System.GC]::Collect()
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()

    Get-PSSession |
    Remove-PSSession -ErrorAction SilentlyContinue

    If ($AdminCredStore)
    {Remove-Item -Path "$env:USERPROFILE\Documents\AdminCredSet.xml" -Force}
    Else
    {
        Write-Warning -Message "`n`t`tYou decided not to delete the custom Admin credential store.
        This store is only valid for this host and user $env:USERNAME"
    }

    Write-Warning -Message "`n`t`tRemoving the displayed session specific variable ojects"

    Compare-Object -ReferenceObject (Get-Variable) -DifferenceObject $AutomaticVariables -Property Name -PassThru |
    Where -Property Name -ne 'AutomaticVariables' |
    Remove-Variable -Verbose -Force -Scope 'global' -ErrorAction SilentlyContinue
    Remove-Variable -Name AdminCredStore -Verbose -Force
}

关于powershell - PowerShell Try/Catch/Finally 脚本中的最佳实践?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63553792/

10-13 07:46
查看更多