powershellcompareobject

Import-Csv data parse to array


I have a CSV file which contains multiline in some cells. I will use this data to compare the value got it from powershell.

This returns differences between the object, however the value is the same.

Expected Results should return nothing because both values are the same.

CSV content:

Value
System\CurrentControlSet\Control\ProductOptions
System\CurrentControlSet\Control\Server Applications
Software\Microsoft\Windows NT\CurrentVersion

Code:

PS> $data = Import-Csv .\tr.csv

PS> $data.Value
System\CurrentControlSet\Control\ProductOptions
System\CurrentControlSet\Control\Server Applications
Software\Microsoft\Windows NT\CurrentVersion

PS> $regval = ((Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\SecurePipeServers\winreg\AllowedExactPaths).machine | Out-String).Trim()

PS> $regval
System\CurrentControlSet\Control\ProductOptions
System\CurrentControlSet\Control\Server Applications
Software\Microsoft\Windows NT\CurrentVersion

PS> Compare-Object $data.Value $regval
System\CurrentControlSet\Control\ProductOptions...                                                                                                  =>
System\CurrentControlSet\Control\ProductOptions...                                                                                                  <=

PS> $Tostring = ($data.Value | out-string).Trim()

PS> Compare-Object $Tostring $regval

InputObject                                                                                                                                         SideIndicator
-----------                                                                                                                                         -------------
System\CurrentControlSet\Control\ProductOptions...                                                                                                  =>
System\CurrentControlSet\Control\ProductOptions...                                                                                                  <=


PS> $Tostring.Length
145

PS> $regval.Length
147

Solution

  • The likeliest explanation is that:

    The most direct fix is to remove the CR chars. from $regval (you can use "`r" in PowerShell to generate a CR char):

    # ...
    
    # Remove all CRs from $regval.
    # Note that not providing a replacement string (missing 2nd RHS operand)
    # default to the empty string, which effectively *removes* what was matched.
    $regval = $regval -replace "`r"
    
    # Should now work as expected.
    Compare-Object $data.Value $regval
    

    That said:


    As for what you tried:

    $Tostring = ($data.Value | out-string).Trim()

    If $data.Value is a single string that doesn't have a trailing newline - whether or not it has embedded newlines - the above is an effective no-op: