简体   繁体   中英

Foreach loop to get department name in powershell office365

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
useremail1@mydomain.com
useremail2@mydomain.com
useremail3@mydomain.com
useremail4@mydomain.com

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM