powershell Try/Catch/Finally脚本的最佳实践



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

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默认变量。

不要这样做。

在每次会话运行时,收集变量中的默认值和自动值,然后在会话结束前将该变量集合与您创建的变量进行比较,只删除您创建的。

所以,在我的情况下,我会使用,比如。。。

$panVariableName 

然后

Remove-Variable -Name 'pan*' -Force

或者如果你不想这样做。在会话开始时,执行以下操作。。。

$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:USERPROFILEDocumentsAdminCredSet.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
}

我相信你可以使用:

Clear-Variable * -Scope Global

Remove-Variable * -Scope Global

或者,确定流程范围会解决您的问题吗?您可以创建一个CCD_ 2并用";呼叫话务员";(&(。这将在独立于全局环境的作用域环境中运行进程。它看起来像这样:

$scriptBlock = { 
Try {
Write-Host "Scripting start...."
}
Catch {
Write-Warning -Message "[PROCESS] Something wrong happened"
Write-Warning -Message $Error[0].Exception.Message
}
Finally {
[System.GC]::Collect() 
}
}
&$scriptBlock

您不需要删除变量,因为在执行之后,范围内发生的任何变量都已经不存在了。

最新更新