Add user to Azure AD from another Azure AD via powershell - powershell

In the Azure portal I can click Add User and select User in another Windows Azure AD directory to add a user from another directory to the current directory (As long as I have sufficient authorization in both directories).
I'd like to be able to do this via powershell, but it doesn't seem possible since you can only connect to a single directory.
Here's the scenario:
admin#tenant1.onmicrosoft.com is a global admin in both tenant1 and tenant2. In the portal, I can see and manage both directories while logged as admin#tenant1.onmicrosoft.com.
But in powershell, if I do:
$cred = Get-Credential -UserName admin#tenant1.onmicrosoft.com
Connect-MsolService -Credential $cred
I can only see and manage the tenant1 directory. So I tried this:
$cred = Get-Credential -UserName admin#tenant1.onmicrosoft.com
Connect-MsolService -Credential $cred
$user = Get-MsolUser -UserPrincipalName user#myfederateddomain.com
$cred2 = Get-Credential -UserName admin#tenant2.onmicrosoft.com
Connect-MsolService -Credential $cred2
$user | New-MsolUser
But this failed:
New-MsolUser : Unable to create this user because the user principal name provided is not on a verified domain.
At line:1 char:9
+ $user | New-MsolUser
+ ~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [New-MsolUser], MicrosoftOnlineException
+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.PropertyDomainValidationException,Microsoft.Online.Administ
ration.Automation.NewUser
I'm guessing this just isn't possible, but maybe someone can point out something I missed?

Unfortunately, as you had guessed, this functionality is not currently available through Azure AD PowerShell. It is something that we'd like to add in the future, but I don't have an exact timeframe for this yet.
UPDATE 4/14/2018: Sorry - was not monitoring this. There is now a way to invite a user from another tenant to the current tenant using Microsoft Graph. Please see https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/invitation. It still doesn't look like there's any Azure AD PowerShell for this.

Related

Powershell : Connect-partnercenter Error: ClientId is not a Guid

Here is my problem, I want to get the list of people with administrator role on O365 partner center while going through Azure Automation for scheduled task.
One of the first problems, is that access to the partner center is that you have to have the MFA activated on the account that does it. So I created an Azure application by following the information here: https://www.cyberdrain.com/connect-to-exchange-online-automated-when-mfa-is-enabled-using-the-secureapp-model/
The application has been created successfully, so I run the command given on the Microsoft site at the bottom (https://learn.microsoft.com/en-us/powershell/partnercenter/multi-factor-auth?view= partnercenterps-3.0):
$credential = Get-Credential
$refreshToken = '<refreshToken>'
Connect-PartnerCenter -ApplicationId 'xxxx-xxxx-xxxx-xxxx' -Credential $credential -RefreshToken $refreshToken
The problem is that when I run this command, this is the message I get:
Connect-PartnerCenter : Error: ClientId is not a Guid.
At line:8 char:1
+ Connect-PartnerCenter -ApplicationId $ApplicationId -Credential $cred ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-PartnerCenter], MsalClientException
+ FullyQualifiedErrorId : Microsoft.Store.PartnerCenter.PowerShell.Commands.ConnectPartnerCenter
I have searched everywhere, I do not understand where this problem comes from.
Have some of you already encountered this problem or have another solution to get the list of admin people on the partner center?
Thank you

Connecting MFA account to multiple CMDlets

I am trying to connect to three different CMDlets with one login:
$credential = Get-Credential
Connect-MsolService -Credential $credential
Connect-ExchangeOnline -Credential $credential
Connect-AzureAD -Credential $credential
it prompts for login, it prompts for old credentials then prompts for MFA, seems to connect to exchange online but returns the following error:
New-ExoPSSession : One or more errors occurred.
At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\netFramework\ExchangeOnlineManagement.psm1:475 char:30
+ ... PSSession = New-ExoPSSession -ExchangeEnvironmentName $ExchangeEnviro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-ExoPSSession], AggregateException
+ FullyQualifiedErrorId : System.AggregateException,Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession
Could I please have assistance to connect these three cmdlets at one please?
Using $credential = Get-Credential, then pass $credential to the commands to login, this way will not work both for Connect-ExchangeOnline and Connect-AzureAD, you just got the error from Connect-ExchangeOnline as the error interrupted the script. For Connect-MsolService, when passing $credential, it will promote you to login interactively again.
In your case, you may need to login for all of them with an MFA-enabled account. If you want to avoid interactively login, you could use Azure AD App to login the commands.
Reference:
App-only authentication for unattended scripts in the EXO V2 module
Using a Service Principal to connect to a directory in PowerShell

Azure Provisioning - Without manual login

I have a Powershell script which runs to set up Azure web apps, databases, etc. but before running the script, I have to do the following:
PS C:/> Login-AzureRmAccount
This pops up a GUI in which I have to manually add in my user, password, and my 2-factor authentication code. I eventually want to use that script as a part of a part of a build/deployment automation script.
I gleaned the following from a few articles about using a "service principal".
First I do:
PS C:\> Add-AzureRmAccount
In this call I have to put in my user, password, and authentication code
After that I have to do the following (even though I don't fully understand).
$app = New-AzureRmADApplication -DisplayName "GGReal" -HomePage "https://www.example.org/ggreal" -IdentifierUris "https://www.example.org/ggreal" -Password "mysecretpass"
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
This seems to work:
Then I try this, and it fails.
New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $app.ApplicationId
I got the following error:
New-AzureRmRoleAssignment : AuthorizationFailed: The client jay#myemail.com' with object id '8ee9a6ec-yyyy-xxxx-xxxx-4ac0883f2a12' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/5ba06de5-xxxx-zzzz-yyyy-27f7d2c8bba6'.
At line:1 char:1
+ New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmRoleAssignment], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand
What do I have to do to enable a scripted authorization without manual intervention?
According to the exception that it indicates that you don't has adequate permission to that. We can check active directory permissions following the document. Our account needs to have Microsoft.Authorization/*/Write access to assign an AD app to a role. That means our account should be assigned to the
Owner role or User Access Administrator role. If not, please ask your subscription administrator to add you to User Access Administrator role. How to add or change Azure administrator roles please refer to the document.
After that please have a try to Automate login for Azure Powershell scripts with the following code.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal
I also find some related documents about creating authentication and Built-in roles:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal
https://learn.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles#roles-in-azurel
Well, you don't have permissions to assign that role to that serviceprincipal, you need appropriate rights. And those would be: Microsoft.Authorization/roleAssignments/write and scope /subscriptions/5ba06de5-xxxx-zzzz-yyyy-27f7d2c8bba6
You could either create a new Custom Role and assign it to your account, or assign something like Subscription Admin (not sure if its the least possible approach, but you can retract it later) to your account.

Run BAT file as a Local User Account

I pulled this from another question, but I cannot seem to make this work.
I need to run this .bat file as a local admin account. I want users to be able to run and install this without having local admin rights.
I'm not sure what's wrong though.
$username = 'localadmin'
$password = 'passwordforlocaladmin'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process -Filepath "p:\kaceInstaller\kaceinstall3.bat" -Credential $credential
The error I'm getting back is:
Start-Process : This command cannot be executed due to the error: The directory
name is invalid.
At P:\kaceInstaller\misc\kaceSetup.ps1:7 char:14
+ Start-Process <<<< cmd -Credential $credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommandy
If you want to allow users to run something as a local administrator account without effectively giving them the password to the local admin account, I would suggest to create a scheduled task running as a local admin. Users can manually trigger that task, which will then be executed under the local admin account. Creating the task withoug saving the credentials should work, but even if you have to save the credentials they won't be accessible to your users.
For access to network shares you may need to connect/disconnect the share with explicit credentials from within the script that the scheduled task runs, though, because the local account usually doesn't have permission to access the network drives mapped by your domain user.
net use X: \\server\share\kaceInstaller password /user:DOMAIN\user
call X:\kaceinstall3.bat
net use X: /d
Make DOMAIN\user a dedicated account that has access only to \\server\share and nothing else to minimize risk.
Note that you must make sure that the script run by the task is not writable by regular users, otherwise they will be able to run arbitrary commands with admin privileges by simply modifying the script.

Connect-MsolService error after importing MSOnline module

I'm receive the following error when I run Connect-MsolService -
Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
+ CategoryInfo : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
+ FullyQualifiedErrorId : 0x80090345,Microsoft.Online.Administration.Automation.ConnectMsolService
+ PSComputerName : xxxxx
Background -
I am using powershell to manage Active Directory, Exchange and Sharepoint Online user data. I have an SSIS package that dynamically builds arguments passed to powershell scripts for creating new and updating existing AD user data, adding/updating necessary security and distribution groups for each user, enabling exchange mailboxes, and passing custom attribute data to Sharepoint online user profiles.
In effort to maintain the purity of the SQL server running the SSIS package, dynamic sessions are created to servers having the modules necessary for import. This allows me to do all of the things mentioned above without having to install the different modules on my SQL server.
My final hurdle is automating the Office 365 licensing. To script licensing assignments I create a session to our server having the necessary MSOnline module and import it giving me access to the Cmdlets, like Set-MsolUserLicense. However, before I can use the Cmdlets I have to connect to the MSOLService.
When I run Connect-MsolService, the credentials modal pops as expected, the appropriate credentials are entered (which have been verified a thousand times over), and I receive the error shown above.
These commands all work fine when I run them from the server where the MSOnline cmdlets are installed, but return the error when run post successful import-module on my SQL server.
Here are the commands used for establishing the session and importing the MSOnline module -
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $securePassword
$outputSession = $Null
foreach($session in Get-PSSession){
if(($session.ComputerName -eq $Server) -and ($session.Availability -eq "Available")){
$outputSession = $session
}
}
if ($outputSession -eq $Null){
$outputSession = New-PSSession -ComputerName $Server -Credential $cred -Name 'MSOnline'
Invoke-Command -Session $outputSession -ScriptBlock {Import-Module MSOnline}
Import-PSSession -session $outputSession -module MSOnline -AllowClobber
}
Connect-MSOLService is the only Cmdlet giving me an issues using these methods. Any help you can provide will be appreciated.
Sigh. This appears to be a bug with single sign on assistant and MSOL module. I have had this issue reproduced reliably and had it reported to Office 365 support. It went nowhere. To state it simply, Connect-MSOnline works only in local sessions.
Mind you, MSOL module is a very strange beast, it is not using PSSession to maintain connection with Azure but uses some internal mechanisms that must rely on single sign-on assistant. This may be why in remote session MSOL commandlet cannot connect to Azure AD.
It was a dead end for me, and the only way to work around it is to write an application that runs on the server using MSOL module and accepts commands from the client or is invoked on server directly via service or scheduled task.