PowerShell脚本中的变量清理

时间:2014-06-22 09:40:15

标签: powershell

在控制台上运行PowerShell脚本时,作用域有助于防止脚本变量流入全局环境。但是,这似乎并不适用于PowerShell ISE。因此,我一直在尝试提供一种简单的方法来跟踪脚本中的变量,以便在脚本退出时可以清除它们。我写的一个测试脚本是为了证明这一点,如下所示:

# Start from clean screen.
Clear-Host

# Set initial variables.
$Var1 = 1
$Var2 = 2
$Var3 = 3

# Initialize variables list.
$VarsList = New-Object System.Collections.ArrayList

# Function to add a variable.
function NewVar
{
    $VarsList.Add($Args) | Out-Null
}

# Add initial variables to $VarsList.
'Var1','Var2','Var3' | ForEach-Object {NewVar $_}

# Check VarsList
Write-Host "VarsList:"
$VarsList
Write-Host ""

# Add a new variable to test NewVar.
$Var4 = 4
NewVar Var4

# Check VarsList
Write-Host "VarsList after Var4:"
$VarsList
Write-Host ""

# Function to remove variable from environment and variables list.
function KillVar
{
    Remove-Variable $Args -Scope 1
    $VarsList.Remove($Args[0])
}

# Function to remove all variables.
function VarGenocide
{
    $VarsList | ForEach-Object {Remove-Variable $_ -Scope 1}
    Remove-Variable VarsList -Scope 1
}

# Try to use KillVar
KillVar Var3

# Check Variables
Write-Host "Variables after KillVar Var3:"
Write-Host "Var1 $Var1"
Write-Host "Var2 $Var2"
Write-Host "Var3 $Var3"
Write-Host "Var4 $Var4"
Write-Host ""

# Check $VarsList
Write-Host "VarsList after KillVar Var3:"
$VarsList
Write-Host ""

# Try to remove all variables
VarGenocide

# Check Variables
Write-Host "Variables after VarGenocide:"
Write-Host "Var1 $Var1"
Write-Host "Var2 $Var2"
Write-Host "Var3 $Var3"
Write-Host "Var4 $Var4"
Write-Host ""

# Check $VarsList
Write-Host "VarsList after VarGenocide:"
$VarsList

删除变量似乎不是问题。但是,更新$VarsList删除的变量似乎比我预期的更难。这是上述脚本的输出。

enter image description here

正如您所看到的,当我使用'Var3'时,$VarsList未从KillVar移除。这导致在尝试VarGenocide时出现“无法找到变量”错误。

我觉得这与变量范围有关。但是,我不确定如何正确处理它,因为我没有使用PowerShell的内置数组类(请参阅here了解原因)。我是对的,有办法解决这个问题吗?还是我还没有看到另一个问题?

我在Windows 8.1上使用PowerShell 4.0,但我非常确定它在XP上应该有效至2.0。

1 个答案:

答案 0 :(得分:2)

函数NewVar有一个微妙的错误。 $Args是一个数组,因此$VarsList.Add($Args)不添加字符串(变量名),它会添加数组。稍后你在那里搜索一个字符串 Var3 ,但是找不到它。

解决此问题的一种方法是使用AddRange代替Add

# Function to add a variable.
function NewVar
{
    $VarsList.AddRange($Args)
}

请注意,您可以省略| Out-Null,因为AddRange无效。顺便说一句,丢弃输出的最有效方法是$null = ...