Foreach loop to get department name in powershell office365

爷,独闯天下 提交于 2019-12-11 06:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!