Home > Back-end >  PowerShell - Add imported csv column into newly exported csv
PowerShell - Add imported csv column into newly exported csv

Time:12-14

I was hoping someone can help me out. I am trying to get the date a license was assigned to a user and export it to a new csv. The import csv contains the UserPrincipalName. I was able to narrow down to only show which license I want but having the UPN show next to the license/date would complete this script. Thanks in advance

$getusers = Import-csv -Path 'C:\test\userlist.csv'

foreach ($user in $getusers) {

    (Get-AzureADUser -searchstring $User.UserPrincipalName).assignedplans | where {$_.Service -eq 'MicrosoftOffice'} | Select-Object Service,AssignedTimeStamp |
    

    Export-CSV -Path "C:\test\userlist-export.csv" -notypeinformation



}

CodePudding user response:

I would do it this way, first querying the user and storing it in a variable and then filter the AssignedPlans where Service = MicrosoftOffice. To construct the objects you can use [pscustomobject]. Worth noting, the call to Export-Csv should be the last statement in your pipeline (it shouldn't be inside the loop), otherwise you would be replacing the Csv with a new value on each loop iteration instead of appending data.

Import-Csv -Path 'C:\test\userlist.csv' | ForEach-Object {
    $azUser = Get-AzureADUser -ObjectId $_.UserPrincipalName
    foreach($plan in $azUser.AssignedPlans) {
        if($plan.Service -eq 'MicrosoftOffice') {
            [pscustomobject]@{
                UserPrincipalName = $azUser.UserPrincipalName
                Service           = $plan.Service
                AssignedTimeStamp = $plan.AssignedTimeStamp
            }
        }
    }
} | Export-Csv "C:\test\userlist-export.csv" -NoTypeInformation
  • Related