To use PowerShell to manage Microsoft 365 services, you need to initiate a connection to Azure Active Directory first and then run the cmdlets it provides.
Connect-MsolService
It prompts a normal Microsoft login screen for you to sign in. When you are using PowerShell window, one connection should last until you close the window. But if you are using PowerShell ISE or tools like Visual Studio Code to program a block of code to run it’s so inconvenient it pops up every time.
One way to make it easy is to use the PSCredential object. Use something like below at the beginning of your code, you should be able to bypass the login prompt during your code development.
$username = '[email protected]'
$pwd = ConvertTo-SecureString 'realpassword' -asplaintext -force;
$cred = New-Object -TypeName PSCredential -argumentlist $username, $pwd
Connect-MsolService -Credential $cred
##put more msonline codes below
You may consider removing it after you are done your coding though. Hard coded credentials in the code base is never a good practice.
If it’s a script for techs to use, I usually put in something a bit lazy:
$upn = get-aduser $env:username | select -expandproperty userprincipalname
$creds = get-credential $upn; connect-msolservice -credential $creds
Just means people don’t have to enter their email haha, without any security risk! 🙂
You can do something similar with Azure cmdlets (remove get-credential as it doesn’t support MFA)
For me, this does not work. The “Connect-MsolService” call simply ignores the passed credentials as if they weren’t specified at all.
Maybe this is because I specified an account with activated 2FA.
any solution for it ?
This doesn’t work for me either. I send my credentials, but it still brings up a window asking me to sign into my Microsoft account, which kind of defeats the point. I then input the very same credentials and it signs me in. Strange that it doesn’t work for me, but well that’s just my luck
Do you have any update ? is there a way to fix this issue?
Thank you for the support