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

321 Views Asked by At

Hi I hope someone can point me in the correct direction here.

I am trying to create some PS 5.1 code that can compare get-variable output at the start of a script with get-variable output generated when there is a error.

I would like to display name-value object information only if a new variable is created OR if its value differs from that generated at the start of the script.

I thought this would be fairly easy using compare-object but i am having difficulty getting this to work with value changes:

$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

Any help would be appreciated.

2

There are 2 best solutions below

1
On BEST ANSWER

I don't know why, but it seems to work if I only select the Name and Value properties from Get-Variable

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
0
On

Final Code i used for anyone interested based on Daniels comment above.

$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