Search code examples
powershellcompareobject

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


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.


Solution

  • 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