Link to home
Start Free TrialLog in
Avatar of YMartin
YMartin

asked on

Powershell update value with concatenated objects

I am trying to update the UPN for a list of users in O365.  I have connected via Powershell and am able to update individual entries however my Powershell is not strong enough to do them all in one shot.

Get-MsolUser | where-object {$_.UserPrincipalName -eq ($_.firstname) +
"." + ($_.lastname) + "@domain.com"} | Set-MsolUserPrincipalName -NewUserPrincipalName ($_.firstname.substring(0,1)) + ($
_.lastname) + "@domain.com"

you cannot call a method on a null-valued expression.
At line:1 char:1
+ Get-MsolUser | where-object {$_.UserPri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

basically trying to set the UPN to first initial + lastname instead of the firstname.lastname.  I have fixed dirsync to create the UPN this way however need to fix all the users which are set the wrong way.  Any help with the code would be appreciated.
Avatar of becraig
becraig
Flag of United States of America image

Something like this should work but not tested.

Get-MsolUser | where-object {$_.UserPrincipalName -eq ($_.firstname) | %  {
$nuname = ($_.firstname.substring(0,1)) + ($_.lastname) + "@domain.com"
Set-MsolUserPrincipalName -NewUserPrincipalName $nuname 
}

Open in new window

Avatar of YMartin
YMartin

ASKER

The problem is that the set-msoluserprincipalname also requires the old userprincipalname.  Both would need to be stored in the variable and be called individually.  Tried to accomplish this but it did not work for me.  It would have piped it for my command but with your version it would need to be saved to the variable.
You already have the UserPrincipalName going through the pipeline, $_.UserPrincipalName. The brackets are messed up though.
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yup I did forget to add the piece footech thanks .
Get-MsolUser | where-object {$_.UserPrincipalName -eq ($_.firstname) | %  {
$nuname = ($_.firstname.substring(0,1)) + ($_.lastname) + "@domain.com"
Set-MsolUserPrincipalName  -Userprinicpalname $_.UserPrincipalName -NewUserPrincipalName  $nuname 
}
                                          

Open in new window

Avatar of YMartin

ASKER

Thanks footech.  That worked.  Sorry I was not able to get the code from becraig to work but I appreciate the help.