office 365 powershell login with service principal or OAuth2 - powershell

I can find information about how to create Service Principals for Office365 with Powershell - but I can't find any how to login with them in Powershell. Is this not possible? I am currently using this code, that works with my Admin account but not with service credentials (that work with Azure) :
$AdminName = "application-id"
$Pass = ConvertTo-SecureString "application-key" -AsPlainText –Force
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
# Azure Login working
#$tenantId = "tenant-id"
#Add-AzureRmAccount -Credential $Cred -ServicePrincipal -TenantId $tenantId
# MSOnline / Office365-Login not working
Import-Module MSOnline
Connect-MsolService -Credential $Cred
The error I get at the "Connect-MsolService" is :
Connect-MsolService : Unable to authenticate your credentials. Make
sure that your user name is in the format: <username>#<domain>. If
this issue persists, contact Support.
Connect-MsolService -Credential $Cred
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
FullyQualifiedErrorId : 0x80048862,Microsoft.Online.Administration.Automation.ConnectMsolService

Related

PowerShell Script Issue New-EXOPSSession : unknown_user_type: Unknown User Type

Running the following Powershell script to try to connect to Gov Azure AD:
Add-Type -Path ".\Source\Binaries\Microsoft\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
Import-Module ".\Source\Binaries\Microsoft\Microsoft.Exchange.Management.ExoPowershellModule.dll"
$username = "email#businessdomain.onmicrosoft.us"
$password = ConvertTo-SecureString "testemailpassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $password)
$connectionURI = "https://ps.compliance.protection.office365.us/powershell-liveid/"
New-EXOPSSession -ConnectionUri $connectionURI -Credential $cred
But seeing this error come back
New-EXOPSSession : unknown_user_type: Unknown User Type
At line:9 char:1
+ New-EXOPSSession -ConnectionUri $connectionURI -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-ExoPSSession], AdalException
+ FullyQualifiedErrorId : Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException,Microsoft.Exchange.Management.E
xoPowershellSnapin.NewExoPSSession
I am able to run this similar script for a non-government environment (https://ps.compliance.protection.outlook.com/powershell-liveid/ as my URI) and see that I successfully connect without error
Please make sure the credentials (username and password )provided are correct and not having any special characters in them while using in the script and make sure to use latest microsoft exchange online module of v2 .
Try to get the credential first , then pass them in the connection segment.
$cred=get-credential
Connect-ExchangeOnline -Credential $cred -ShowProgress $true
$connectionURI = "https://ps.compliance.protection.office365.us/powershell-liveid/"
New-EXOPSSession -ConnectionUri $connectionURI -Credential $cred -ShowProgress $true
Or please try to use command as for non mfa account by using credential and dont credentials for mfa enabled account
$UserCredential = Get-Credential
Connect-IPPSSession -Credential $UserCredential
Or something like this SO refrence
Note: If ExchangeEnvironmentName is used, ConnectionUri parameter is
not required.
Use the stored variable name ($UserCredential) for this parameter .
• You can try below command which connects to Exchange Online PowerShell in a Microsoft GCC High organization:
Connect-ExchangeOnline -Credential $UserCredential -ShowProgress $true -ExchangeEnvironmentName O365USGovGCCHigh
In case, if the account you are using has MFA enabled use
userprincipal name.
Example:
Connect-ExchangeOnline -UserPrincipalName lxxra#xxxxxairlines.us -ExchangeEnvironmentName O365USGovGCCHigh
To connect to Microsoft 365 DoD organization replace environment name with O365USGovDoD to this Connect-ExchangeOnline -UserPrincipalName xxxx#contoso.com -ShowProgress $true
Give your user name correctly and Microsoft authenticator will authenticate if mfa enabled.
References:
Connect to Exchange Online PowerShell | Microsoft Docs
addazureaccount-unknownusertype | social.msdn.microsoft.com

Powershell "Connect-PowerBIServiceAccount" error

I'm experiencing an issue concerning this command (Connect-PowerBIServiceAccount), I everytime get the same error :
Connect-PowerBIServiceAccount : Failed to populate environments in settings
Au caractère Ligne:1 : 1
Connect-PowerBIServiceAccount
CategoryInfo : WriteError: (Microsoft.Power...IServiceAccount:ConnectPowerBIServiceAccount)
[Connect-PowerBIServiceAccount], Exception
FullyQualifiedErrorId : Failed to populate environments in settings,Microsoft.PowerBI.Commands.Profile.ConnectPowerBIServiceAccount
I've tried various things already like :
$password = "mypassword" | ConvertTo-SecureString -asPlainText -Force
$user = "surname.name#company.com"
$credential = New-Object System.Management.Automation.PSCredential($user, $password)
Connect-PowerBIServiceAccount -Credential $credential
or
Connect-PowerBIServiceAccount -Environment Public
or
Connect-PowerBIServiceAccount -TenantId "company.com" -ServicePrincipal -Credential (Get-Credential)
I get the same result as well with Login-PowerBI or Login-PowerBIServiceAccount.
And I can't use -CertificateThumbPrint, I don't have access to the Power BI liscence key of my company.
All the PowerBI modules for PowerShell are installed (and I tried as well reinstalling them), my current version of Powershell is 5.1.19041.1645 and my .NET Framework version is 4.8
If you have any clue they are welcome.

How to request a certificate from a CA on a remote machine using PowerShell?

I am trying to invoke a PowerShell command on a remote computer. I'd like to request a certificate from an in-house CA. If I run the following command directly on the remote PC the operation is successful:
Get-Certificate -Template 1.3.6.1.4.1.311.21.8.9612972.3074733.7357589.1249582.14248002.117.5480590.5436517 -Credential $cred -Url ldap: -CertStoreLocation Cert:\LocalMachine\My
When I run the following command from a remote computer on the same domain I get the WIN32: 87 error shown below. I have googled the error extensively and cannot figure out the issue (fyi.. I have mitigated the double hop issue earlier in my script by using Enable-WSManCredSSP).
$user = 'ABCCOmpany\<password>' #We are using the local machine's Administrator account
$password = ConvertTo-SecureString '<password>' -asplaintext -force
$credential = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $user, $password
$RequestAndReceiveCertificateSuccessful = Invoke-Command -Session $s -ScriptBlock{param($cred) Get-Certificate -Template 1.3.6.1.4.1.311.21.8.9612972.3074733.7357589.1249582.14248002.117.5480590.5436517 -Credential $cred -Url ldap: -CertStoreLocation Cert:\LocalMachine\My} -ArgumentList $credential
Error:
The parameter is incorrect. 0x80070057 (WIN32: 87 ERROR_INVALID_PARAMETER)
+ CategoryInfo : NotSpecified: (:) [Get-Certificate], Exception
+ FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.GetCertificateCommand
+ PSComputerName : Agent3

Add-AzureRmAccount : Sequence contains no element (Not working for Gmail accounts too)

I have created a 'Free Trial' account with my personal email ID which is a Gmail ID. I'm getting the error :
Add-AzureRmAccount : Sequence contains no elements At line:1 char:1
+ Add-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand
The code I'm running is
$username = "abc#gmail.com"
$password = "something"
$secpass = $password | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secpass
Add-AzureRmAccount -Credential $cred
Are there certain type of accounts/subscriptions for which logging in like this is supposed to work?
Windows Live ID credentials cannot be used for a non-interactive login. This error message is described as part of this issue which has been raised because it needs improving.
I think you either need to use Login-AzureRmAccount to login interactively or create a Service Principal for login, per this guide: https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azurermps-4.2.0
Log in with a service principal
Service principals provide a way for you to create non-interactive
accounts that you can use to manipulate resources. Service principals
are like user accounts to which you can apply rules using Azure Active
Directory. By granting the minimum permissions needed to a service
principal, you can ensure your automation scripts are even more
secure.
If you don't already have a service principal, create one.
Log in with the service principal:
Login-AzureRmAccount -ServicePrincipal -ApplicationId "http://my-app" -Credential $pscredential -TenantId $tenantid

Running Set-AzureRmAppServicePlan from Automation script (RunBook)

I'm trying to run Set-AzureRmAppServicePlan from automation runbook but getting
Set-AzureRmAppServicePlan : Run Login-AzureRmAccount to login. At
line:20 char:1
+ Set-AzureRmAppServicePlan -ResourceGroupName "...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-AzureRMAppServicePlan], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.WebApps.Cmdlets.AppServicePlans.SetAzureAppServicePlanCmdlet
Note that actual runbook authentication using Automation Credential is successful.
And I can run this script from local powershell using
Login-AzureRmAccount
Add-AzureRmAccount
Set-AzureRmAppServicePlan...
Is it possible at all to run this from automation without interactive login?
Thanks
Pavel
figure it out.. pretty simple instead of
Add-AzureAccount - which is used in sample runbook Get-AzureVMTutorial created automatically
need to use
Add-AzureRmAccount
for use with Azure Resource Manager cmdlet requests like
Set-AzureRmAppServicePlan
Leaving question / answer here.. might still help someone
If you are not using MFA, pls see the following cmds, replace 'yourPassword', 'yourUserName', 'yourEnvironment', 'yourSubscriptionId', 'yourTenantId' with your own message and put it to your script then you can login without interactive page.
$userPassword = ConvertTo-SecureString -String "yourPassword" -AsPlainText -Force
$psCred = new-object -typename System.Management.Automation.PSCredential -argumentlist 'yourUserName', $userPassword
$credential = Get-Credential -Credential $psCred
add-azureRmAccount -EnvironmentName 'yourEnvironment' -credential $credential -subscriptionId 'yourSubscriptionId' -tenant 'yourTenantId'