• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 41
  • Last Modified:

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

0
Rob Shorts
Asked:
Rob Shorts
2 Solutions
 
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
 
Rob ShortsAuthor Commented:
Thanks both!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now