1
votes

I am trying to get the department from a list of UserPrincipalNames

I am able to get this to work for a single user outside of the foreach loop. Its adding the loop where I am having trouble.

Connect-MsolService
$users = Import-Csv C:\Users\me\Desktop\users.csv

foreach ($user in $users){

Get-MsolUser -UserPrincipalName $user | Select-Object firstname, lastname, UserPrincipalName, department |Export-Csv C:\Users\me\Desktop\test.csv

}

There are 50 email addresses listed in the CSV one email address per line. With the first line being "UserPrincipalName"

CSV Sample Data

userprincipalname
[email protected]
[email protected]
[email protected]
[email protected]
2
What isn't working? I tried exactly your example and it returned results as expected. Please provide any error messages or explain what you expected vs what the results were. - Dusty Vargas
The code as presented will not emit all users with the requisite information into the destination TEST.CSV. (In fact, the CSV will be empty with the code as given.) See my answer below. - Jeff Zeitlin
You gave Export-Csv nothing to export - vrdse
Yeah the export-csv was in the wrong place, but even without it I get the error Get-MsolUser : User Not Found. User: @{[email protected]} - rulecombination
you are using $user as your UPN ... but that came from importing a CSV. that means it will be an OBJECT with at least one property that has at least one value. what happens if you use $User.PropertyNameThatContainsTheUPN? - Lee_Dailey

2 Answers

0
votes

Think PowerShell - the pipeline uses objects, and you have a ForEach-Object cmdlet:

Connect-MSOLService

Import-CSV -Path C:\Users\Me\Desktop\Users.CSV | 
    ForEach-Object { Get-MSOLUser -UserPrincipalName $_.UserPrincipalName | 
        Select-Object firstname, lastname, UserPrincipalName, department } | 
    Export-CSV C:\Users\Me\Desktop\test.CSV

0
votes

In case you need to lookup for data from a csv , then want to use them in a script and export scrip 's result in another CSV

# Importing MsOnline Module           
Import-Module MSOnline
Connect-MsolService


#Import excel document containing our data ,Path "C:\list-email.csv" 
$ImportData = Import-Csv "C:\list-email.csv"

$Output = foreach ( $Data in  $ImportData )
{
    #Storing Email column data in $Data for each row
    write-host $Data.Email
        
    Get-MsolUser -UserPrincipalName $Data.IONEmail | Select-Object UserPrincipalName,LastPasswordChangeTimestamp, Departement
}
#Output the array to the CSV File
$Output | Export-CSV "C:\LastLogonDateExport.csv"