Home > Back-end >  How to read only one column from csv file using Powershell
How to read only one column from csv file using Powershell

Time:12-01

I'm working on powershell script and I'm trying to read only "User" column from my csv file and then convert it to their Microsoft AzureAD Display name but not sure how to do that so I'll be appreciated if I can get any help or suggestion.

My csv file look like this

C:\AuditLogSearch$($CurDate) Final Audit-Log-Records.csv

User       Date &Time       Activity
-------------------------------------
abc@gmail.com   11/22/2021     play soccer
kei@gmail.com   10/22/2021     play football
def@gmail.com   11/22/2021     play soccer
def@gmail.com   09/22/2021     play Baseball
xyz@gmail.com   08/22/2021     play soccer
klm@gmail.com   19/22/2021     play football
function Connect-AzureActiveDirectory {
    $pso = New-PSSessionOption -SkipCACheck:$true -SkipCNCheck:$true -SkipRevocationCheck:$true -OperationTimeout 180000 -ProxyAccessType AutoDetect
    Connect-AzureAD -Credential $credential -ConnectionUri https://outlook.office365.com/PowerShell-LiveID -PSSessionOption $pso
    $host.ui.RawUI.WindowTitle = "Exchange Online - NAM Production Beta MFA"
    Write-Host "Connected to Azure AD"      
}


function Convert-UserColumn {
    $ImportFile = "C:\AuditLogSearch\$($CurDate) Final Audit-Log-Records.csv"
    $ExportFile = "C:\AuditLogSearch\FinalFile.csv"

// I'm struggling with the logic here

    $list = @() foreach ($u in $ImportFile.User) {
        $list  = Get-AzureDisplayName -mail $u
        
    }

    Get-AzureADUser -ObjectId 

   | Export-Csv $ExportFile -NoTypeInformation
}

Trying to make the Final Export csv file should look like this C:\AuditLogSearch\FinalFile.csv

User       Date &Time       Activity
-------------------------------------
Jonathan Sparkle   11/22/2021     play soccer

Randy Mod       10/22/2021     play football
Hanah P         11/22/2021     play soccer
Hanah P         09/22/2021     play Baseball
Cristiano Ronaldo   08/22/2021     play soccer
Leo Messi    19/22/2021     play football

CodePudding user response:

You can just update the values on the User property of the imported CSV, there is no need to create a $list = @() to save the results.

Assuming $ImportFile.User contains valid UserPrincipalNames of Azure AD Users, the part you're struggling with would look like this (definitely no need for a function):

$ImportFile = Import-Csv "C:\AuditLogSearch\$($CurDate) Final Audit-Log-Records.csv"
$ExportFile = "C:\AuditLogSearch\FinalFile.csv"

foreach ($u in $ImportFile) {
    $u.User = (Get-AzureADUser -ObjectId $u.User).DisplayName
}

$ImportFile | Export-Csv $ExportFile -NoTypeInformation
  • Related