Search code examples
powershellcompareimport-csvselect-object

Creating new column in csv using powershell with dynamic values


Hi I am trying to compare two csv and see the delta between them. I want to create a new column in the csv to capture deactivated and new users comparing the old and new data extract.

Though I am able to create new column unable to populate values into the new column. Here User_status is the column I am creating and it should hold deactivated value.

Here is a small portion of my code to see the deactivated users:

if ($csv2.UserID -match $user.UserID)
{
    Write-Verbose "$user.UserID is in both files"
}
else
{
    Write-Verbose "$user.UserID is missing from csv2"
    $missing += $user
    $user_status = 'Deactivated'
    #Set-Variable -Name "user_status" -Value "Deactivated"
    $missing | Select-Object *,@{Name='User_Status';Expression= { $_.user_status  } } |Export-Csv -path "C:\Users\test.csv" -NoTypeInformation 

}

Solution

  • You set the variable $user_status but then add $_ when trying to call it. Instead just use the variable you populated

    if ($csv2.UserID -match $user.UserID)
    {
        Write-Verbose "$user.UserID is in both files"
    }
    else
    {
        Write-Verbose "$user.UserID is missing from csv2"
        $missing += $user
        $user_status = 'Deactivated'
        #Set-Variable -Name "user_status" -Value "Deactivated"
        $missing | Select-Object *,@{Name='User_Status';Expression= { $user_status  } } |Export-Csv -path "C:\Users\test.csv" -NoTypeInformation 
    
    }
    

    As pointed out by @zett42, base variables expand fine inside of quotations, whereas accessing properties of a variable requires a subexpression

    Works fine

    "string with a simple $variable"
    

    Requires subexpression

    "string with complex $($variable.property)"