I Have a csv with multiple user which I want to change their City and their mobile phone number (I am just a guy trying to get better at PowerShell and am an absolute beginner so any help apricated) I have imported the CSV file which has headers and am running a for each object loop through my code but when I run the code I get User not found. user: error I have removed the part of my code but I have already imported the MSOnline module and I am running the script as a global admin on the tenant so it not an error with permissioning.
Code:
$csv = Import-Csv -Path "D:\J-O PC\Documents\test.csv" -Delimiter ","
$userid = Out-String -InputObject $csv.userID
$city = Out-String -InputObject $csv.city
$Phone = Out-String -InputObject $csv.phone
ForEach-Object{
Set-MsolUser -UserPrincipalName $userid -City $city -MobilePhone $Phone
}
Error:
Set-MsolUser : User Not Found. User: .
At D:\J-O PC\Documents\James-Oliver\Cloud\test.ps1:11 char:1
+ Set-MsolUser -UserPrincipalName "$userid" -City "$city" -MobilePhone ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [Set-MsolUser], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.UserNotFoundException,Microsoft.Online.Administration.Automation.SetUser
I have imported the CSV file and running a for each object loop through my code I just need to to go through each user principle name(UPN) in the CSV and change the mobile and city in the same line. I have transformed the UPN into a string since it was refusing to accept the variable when running it as an object any advise and help would be greatly appreciated
Your ForEach-Object
is not doing anything, you're supposed to pipe the output from Import-Csv
to it so it actually enumerates the objects. Also, all calls to Out-String
are completely unneeded.
Import-Csv -Path 'D:\J-O PC\Documents\test.csv' | ForEach-Object {
$setMsolUserSplat = @{
UserPrincipalName = $_.userID
City = $_.city
MobilePhone = $_.phone
}
Set-MsolUser @setMsolUserSplat
}
As aside, consider migrating your code to the Microsoft.Graph Module, the MSOnline Module is deprecated and the API it's calling behind the scenes will no longer work in the future. See Important: Azure AD Graph Retirement and Powershell Module Deprecation for more information.
You can use Update-MgUser
as a replacement in this case, the code would look awfully similar:
Import-Csv -Path 'D:\J-O PC\Documents\test.csv' | ForEach-Object {
$updateMgUserSplat = @{
UserId = $_.userID
City = $_.city
MobilePhone = $_.phone
}
Update-MgUser @updateMgUserSplat
}