How to export a new separate csv in PowerShell

Viewed 50

I have an existing csv file that have multiple columns, I'm trying to use the "Owner" column value and check if that user exists in AzureAD or not.

If a user exists then Ignore and if it's not then export it to the new CSV file called $OrphanOneDrive.

I already have this script so far but some reason it's not working yet so I would be really appreciated if I can get any help or suggestion.

I check it using status message because this is how it look if a user in not existed.

enter image description here


$CSVImport = Import-CSV $LitHoldUserSites

ForEach ($CSVLine in $CSVImport) {

    $CSVOwner = $CSVLine.Owner
    try{
        $CheckinAzureAD = Get-AzureADUser -ObjectId $CSVOwner 
    }catch{
        $StatusMessage = $_.Exception.Message
        if($Null -eq $StatusMessage ){
            #Ignore because User Exists
        }else{
            #Export to new csv for every owner that got an error
            $CheckinAzureAD  | Export-Csv $OrphanOneDrive -notypeinformation -force
        }

    }
1 Answers

You already got an answer in the comments but that being said, I want to submit a different take on this problem.

Instead of doing it your way, I would suggest getting all the users first, then working with the local cache of user you just obtained. This should enhance performance since you only have to make a single call to Get-AzureADUser instead of many.


# Getting all users once
$AllUsers = Get-AzureADUser -All $true

$CSVImport = Import-CSV $LitHoldUserSites
$OrphanedUsers = [System.Collections.Generic.List[PSObject]]::new()
ForEach ($CSVLine in $CSVImport) {

    $CSVOwner = $CSVLine.Owner
    # Same as Get-AzureADUser -ObjectId $CsvOwner but we don't have to make that external call anymore
    $CheckinAzureAD = $AllUsers | Where ObjectId -eq $CSVOwner
    if ($null -eq $CheckinAzureAD) {
        # Instead of exporting each users individually, we collect the users
        $OrphanedUsers.Add($CSVLine) 
        Continue 
    }
   
}
# 1 single export vs exporting each users is more efficient.
$OrphanedUsers | Export-Csv $OrphanOneDrive -NoTypeInformation 
Related