Reputation: 15
Having issues with a powershell command, I'm trying to bulk license a group of users but I'm having difficulties getting the output of one command to be the input of another and insight would be greatly appreciated
I first tried
Get-MsolUser -All -UnlicensedUsersOnly -City "city name" | ForEach {Set-MsolUserLicense -AddLicenses "Account SKU"}
then I tried
Get-MsolUser -All -UnlicensedUsersOnly -City "City Name" | select-object UserprincipalName | ForEach {Set-MsolUserLicense -Userprincipalname <String> -AddLicenses "Account SKU ID"}
Upvotes: 1
Views: 1359
Reputation: 437109
Generally, you only need the ForEach-Object
cmdlet (whose built-in alias is foreach
):
for target cmdlets that do not support direct input from the pipeline [with the specific objects provided]
for custom processing of each input object with multiple expressions or commands in a script block ({ ... }
), inside of which automatic variable $_
represents the input object at hand.
Specifically, in your case you do not need a ForEach-Object
call, and while you still can make it work with such a call, as shown in TessellatingHeckler's answer, it is not only needlessly verbose but also significantly slower.
Get-MsolUser
outputs objects of type [Microsoft.Online.Administration.User]
, and Set-MsolUserLicense
's -UserPrincipalName
parameter is designed to implicitly bind to such objects via their .UserPrincipalName
property, so that you can simply pipe Get-MsolUser
output directly to Set-MsolUserLicense
:
Get-MsolUser -All -UnlicensedUsersOnly -City "city name" |
Set-MsolUserLicense -AddLicenses "Account SKU ID"
Upvotes: 1
Reputation: 28963
Get-MsolUser -All -UnlicensedUsersOnly -City "City Name" |
ForEach {
Set-MsolUserLicense -Userprincipalname $_.UserPrincipalName -AddLicenses "Account SKU ID"
}
Upvotes: 0
Reputation: 373
Inside of the foreach you can get access to the current element using
$_
So you can access any property of the current element using the following syntax:
$_.PropertyYouNeed
Upvotes: 0