Powershell - 比较 get-variable 输出并显示是否有任何值更改

Powershell - Comparing get-variable outputs and displaying if any values change

嗨,我希望有人能在这里为我指明正确的方向。

我正在尝试创建一些 PS 5.1 代码,可以将脚本开始时的 get-variable 输出与出现错误时生成的 get-variable 输出进行比较。

我想仅在创建新变量或它的值与脚本开始时生成的值不同时才显示名称-值对象信息。

我认为使用 compare-object 会相当容易,但我很难让它与值变化一起工作:

$PostscriptVar = Get-Variable
$NewVar1 = 1
$Avarchange = Get-Date
$EndscriptVar  = get-variable

#This works for any new variables created.
compare-object $PostscriptVar $EndscriptVar -Property name

#This doesn't work for any change in values - i can't get this to work.
#compare-object $PostscriptVar $EndscriptVar -Property name,value

如有任何帮助,我们将不胜感激。

我不知道为什么,但如果我只 select 来自 Get-Variable

NameValue 属性,它似乎有效
Remove-Variable NewVar1 -ErrorAction SilentlyContinue
$Avarchange = Get-Date
$PostscriptVar = Get-Variable | Select-Object Name, Value
$NewVar1 = 1
$Avarchange = $Avarchange.AddDays(1)
$EndscriptVar = Get-Variable | Select-Object Name, Value

Compare-Object $PostscriptVar $EndscriptVar -Property Name, Value

我根据上面丹尼尔斯的评论为感兴趣的人使用的最终代码。

$PrescriptVar = Get-Variable | Select-Object Name, Value
$NewVar6 = 2
$arraytest = "test1","Test2","Test3"
$Avarchange = $Avarchange.AddDays(1)
$EndscriptVar = Get-Variable | Select-Object Name, Value

#Compare-Object $PrescriptVar $EndscriptVar -Property Name, Value
$NewOrChangedVarObj = Compare-Object $PrescriptVar $EndscriptVar -Property Name, Value | ?{$_.sideindicator -eq '=>'} | Where -Property Name -ne "PrescriptVar" | Where -Property Name -ne "EndscriptVar"

$NewOrChangedVarObj | Select-Object Name, Value | fl