问题
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
回答1:
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
来源:https://stackoverflow.com/questions/57776300/foreach-loop-to-get-department-name-in-powershell-office365