Powershell for loop script for O365 licenses

Hi Experts,

I'm trying to create a powershell script, with a for loop to pull a list of users from a list and get it into a .csv file for a list of users to export Office 365 licenses.

The script I have is only outputting the last user in the list I have.  

Can anyone help with this?

$list = import-csv .\list.csv 

foreach ($User in $List) 
{
Get-MSOLUser -UserPrincipalName $User.userprincipalname | where {$_.isLicensed -eq $true} |select DisplayName,userprincipalname,islicensed,{$_.Licenses.AccountSkuId}| Export-CSV .\O365UserList.csv –NoTypeInformation 
}

Open in new window

Ron ShortsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vasil Michev (MVP)Commented:
You are calling the Export-CSV operation for each iteration, thus only writing one entry at a time. Either store the output in a variable and use Export-CSV outside of the loop, or use Export-CSV with the -Append switch:

$list = import-csv .\list.csv 

foreach ($User in $List) 
{
Get-MSOLUser -UserPrincipalName $User.userprincipalname | where {$_.isLicensed -eq $true} |select DisplayName,userprincipalname,islicensed,{$_.Licenses.AccountSkuId}| Export-CSV .\O365UserList.csv –NoTypeInformation -Append
} 

Open in new window

0
oBdACommented:
Do it "the PowerShell way" and use the pipeline with the ForEach-Object cmdlet instead of the ForEach statement:
$list = import-csv .\list.csv 
$List | ForEach-Object {
	Get-MSOLUser -UserPrincipalName $_.userprincipalname |
		Where-Object {$_.isLicensed} |
		Select-Object DisplayName, userprincipalname, islicensed, @{n='AccountSkuId'; e={$_.Licenses.AccountSkuId}}
} | Export-CSV .\O365UserList.csv –NoTypeInformation

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ron ShortsAuthor Commented:
Thanks both!!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.