Trying to Log in to Azure in Powershell - powershell

I am following the MS guide located here and everything goes through correctly until I have to actually log in. The pop up window appears for my creds and validates them, but powershell doesn't seem to notice.
So it goes Install Module, Import Module, Verify Version, Log in. See below for what happens on the last two steps.
PS C:\WINDOWS\system32> Get-Module AzureRM -ListAvailable | Select-Object -Property Name,Version,Path
Name Version Path
---- ------- ----
AzureRM 6.3.0 C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.3.0\AzureRM.psd1
PS C:\WINDOWS\system32> Connect-AzureRmAccount
Account :
SubscriptionName :
SubscriptionId :
TenantId :
Environment :
PS C:\WINDOWS\system32>
Of course, this prevents me from doing very much else with Azure from that point forward.
Edit: Issue appears on multiple workstations

I got this same issue. I have two users like many of you: the Azure user that is the "Work" account, and then the "Personal" account which is also created automatically by Office365 and Azure. I was getting the issue when I tried to use my "personal" account, in which I have some subscriptions added (delegated).
After trying lots, what worked for me was to login to the "Work" account when the "Connect-AzureRmAccount" command asks for an username/password. Then, I again use the command "Connect-AzureRMAccount", but this time I entered the personal account, and it finally worked.
Picture here
Edit: A better way I found later was this, as I manage a lot of subscriptions/tenants from a single account (delegated access):
Put the “tenantid” into a variable (you can get this ID on the Azure Portal, in my case, on the option to change directories):
How to get your tenant's IDs quickly
$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Login specifying the TenantId:
Login-AzureRmAccount -TenantId $tenantId
Example 2

This behavior happens when you run
Clear-AzureRMContext -Scope CurrentUser
I'm not sure why and im attempting to debug on how to fix the issue. A work around is to close the powershell window and reopen a new powershell windows that does not have this command ran.
Running the command
Enable-AzureRmContextAutosave -Scope CurrentUser
Fixed the issue for me. This will autosave your context for every powershell session. If this is not desired you can run the command
Enable-AzureRmContextAutosave -Scope Process
which will save the azure context for only the process. Otherwise you will need to handle

You can try this...
Install-Module PoweshellGet -Force
Set-ExecutionPolicy -ExicutionPolicy Remotesigned
Install-Module AzureRm
Import-Module -Name AzureRm
Login-AzureRmAccount

You can use the below link to install latest PowerShell version:
https://github.com/Azure/azure-powershell/releases
And then use something like this in order to automatically pass in the username password, and skipping the UI:
$azureAccountName ="enter username here"
$azurePassword = ConvertTo-SecureString "password here" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
Login-AzureRmAccount -Credential $psCred

Have you tried the following:
Import-Module Microsoft.Powershell.Security
$azureAccountName ="enter username here"
$azurePassword = ConvertTo-SecureString "password here" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)
$decrypt = $psCred.GetNetworkCredential()
$ptpass = $decrypt.Password
Write-Output "Logging in to Azure using $azureAccountName with a password of $ptpass"
Login-AzureRmAccount -Credential $psCred
If you receive an error with this code, please comment with the entire error message.

The only thing i can think of is the below
You maybe using Azure Service Management (Azure V1 / Azure Classic) which uses a different module to Azure Resource Manager (ARM , Azure V2).
To install Azure Service Management Module:
Install-Module Azure -AllowClobber
Allowing clobber because you already have AzureRM Module installed
Import Azure Module to PowerShell:
Import-Module Azure
Logs into ASM:
Add-AzureAccount
Shows you all subscriptions
Get-AzureSubscriptions
Selects the Subscription you allocate to work within
Select-AzureSubscription
Answered something similar in the below Thread:
Login-AzureRmAccount return subscription but Get-AzureSubscription return empty
Hope this helps

You can try logging in using the Service Principal credentials.
Service principal is an application created under Active Directory to which you can apply permission rules.
$pscredential = Get-Credential
Connect-AzureRmAccount -ServicePrincipal -ApplicationId "http://my-app" -Credential $pscredential -TenantId $tenantid
Refer here for more details.

Related

Powershell and Teams two factor authentication

I have installed Microsoft Teams PowerShell module and want to connect to my account using the command
$credential = Get-Credential
#Connect to Microsoft Teams
Connect-MicrosoftTeams -Credential $credential
A dialog will popup asking for my credentials only, and without the second step which is a code I receive on my mobile, I can't log in correctly and an error will appear.
My Question is how to bypass the two factor code or how to wait for it?
My attempt is :
I read that using just
Connect-MicrosoftTeams
Would open the Microsoft Login GUI, then inside the window I can sign in and enter the code.
The problem is the above command will throw an error and GUI will not open.
Links:
https://learn.microsoft.com/en-us/microsoftteams/teams-powershell-install
https://learn.microsoft.com/en-us/powershell/module/teams/connect-microsoftteams?view=teams-ps
Thanks in advance for your help.
First Install-Module -Name PowerShellGet -Repository PSGallery -Force
then open a new Powershell window and Update-Module MicrosoftTeams -allowprerelease
You'll get the 2.3.2-preview
then Connect-MicrosoftTeams
now you get your MFA enabled account to work.
The irony, the non preview module cant handle MFA june 14 2021.
/Göran Eriksson

Permissions required to use Move-VM remotely in Hyper-v 2016

I am attempting to run the PowerShell command "move-vm" remotely but I am getting permissions errors that I can't seem to get past.
My move-vm command looks like this:
move-vm -ComputerName SorceHost -Name $vm.name -DestinationHost $DestHost -IncludeStorage -DestinationStoragePath d:\vms -DestinationCredential $cred -Credential $cred
and I am defining the credentials like this
$username = ".\PSAPIUser"
$password = Get-Content 'C:\key\PSAPIAUTH.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
Both the source and destination are on the same AD domain, and I have created a domain admin account specifically for this function. I have added the domain admins group to the local groups 'Hyper-V administrators' 'administrators' on the source and destination hosts. When I issue the command I get:
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer 'SourceHost'.
There are various articles out there about how to do this in 2012, however, its my understanding that the process has changed significantly in 2016 due to the depreciation of something called authorisation manager.
Does anyone have any experience on how to configure permissions to allow remote Hyper-V management with PowerShell specifically in 2016?
Thanks in advance.
Edit:
$cred = Get-Credential
$cred
UserName Password
-------- --------
PSAPIuser#domain.net System.Security.SecureString
move-vm : You do not have the required permission to complete this task. Contact the administrator of the authorization policy for the computer
Managing Hyper-V remotely uses something called Constrained Delegation. Imagine the scenario.
You are on the host Man1, and you are issuing a command to Hyp-001 to move a VM to Hyp-002. So you have Man1 issuing commands to Hyp-001, which is fine as it can use your credentials, but when Hyp-001 passes commands to Hyp-002 it has no credentials to pass, hence you get the error
move-vm : Virtual machine migration operation failed at migration source.
Failed to establish a connection with host 'ng2-vps-011.hyperslice.net': No credentials are available in the security package
to get around this you need to give specific permissions that allows hosts to run specific services on each other, within AD delegation.
From PowerShell it would look like this:
Set-ADObject -Identity $HostDeetsArra.Disname -ADD #{"msDS-AllowedToDelegateTo"="$service1/$Disname","$Service1/$HostName"}
#$disnam = distignushed name, $Service1 is the service 'cifs' $hostanme is the FQDN
In 2016 you also need this:
Set-ADAccountControl -Identity $HostDeetsArra.Disname -TrustedToAuthForDelegation $true
My source for this information is below
https://www.altaro.com/hyper-v/free-powershell-script-configure-constrained-delegation-hyper-v/

Using AzureAD PowerShell CmdLets on TFS Release Manager

I want to execute some PowerShell scripts on our TFS Release Manager environment that use AzureAD module to provision some Azure AD groups. The scripts are executed using an Azure Powershell Task. I've installed the AzureAD module, so the AzureAD PowerShell CmdLets are recognized.
However, for them to work the scripts first needs to connect to AzureAD using the Connect-AzureAD CmdLet. This CmdLet wants to show a modal dialog for entering credentials, which obviously isn't possible in a Release Manager task. I also cannot supply credentials using command line parameters. I want Connect-AzureAD to somehow use the current user context for the connection. Is this possible?
You could use the -Credential option of Connect-AzureAD.
In your AzureAD task, you can use the following code:
```
$pass=ConvertTo-SecureString $Env:password -AsPlainText -Force
$credential=New-Object PSCredential($Env:login, $pass)
Connect-AzureAD -Credential $credential
```
login and password are stored in a secret variable in the release definition.
Alternatively you might get the password from a previous task in the build definition. I that case, in the script arguments of the task, you pass the password -password "$(password)"
and in the `Script or Script inline you have, this time:
``
param([string]$password)
$pass=ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object PSCredential($Env:login, $pass)
Connect-AzureAD -Credential $credential
``
I get the password from KeyVault with the Azure KeyVault task, but that might not be an option for you if you are on premise.
We've found an answer. It had been setting right in front of us on the official Connect-AzureAD documentation page (example 3).
So we're now authenticating using a SPN and a self-signed certificate. This works just fine.

How to login from an Azure Resource Manager Runbook?

Using the new Azure portal, I am trying to add a powershell runbook that will start a specific VM. This is not something that will be run in powershell from my PC, it will instead run as an ARM job. I can't seem to find a way to successfully login.
If running from my desktop in powershell I can just call Login-AzureRmAccount and it will launch a login dialog before running any further steps. From what I've read on the web it seemed that what I needed to do was add a credential to my automation account, retrieve it and then call the same Login method. I've now done that, but still can't log in.
Import-Module AzureRM.Compute
$AutomationCredentialAssetName = "automation"
$Cred = Get-AutomationPSCredential -Name $AutomationCredentialAssetName
Write-Output $Cred
Login-AzureRmAccount -Credential $Cred
Start-AzureRmVm -Name 'myvmname' -ResourceGroupName 'myresourcegroupname'
The credential is being retrieved correctly (get's written to output) but the call to the Login-AzureRmAccount fails with:
Login-AzureRmAccount : unknown_user_type: Unknown User Type
At line:10 char:1
+ Login-AzureRmAccount -Credential $Cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Common.Authentication.AadAuthenticationFailedException,Microsoft.Azure.Com
mands.Profile.AddAzureRMAccountCommand
If I don't attempt to log in first I get a message telling me to call Login-AzureRmAccount first.
How do I authenticate from within a runbook so that I can run automation tasks? What am I doing wrong?
We have subsequently discovered the the automation account created a connection when created that can be used to login:
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
At a guess you are trying to log in with a Microsoft account, which can only be done interactively (as it needs to redirect through live.com). You will need to create a user within the tenant (Active Directory) that you are authenticating against in order for non-interactive login to work.
The easiest method to make this work is to create an account in the old portal (the new portal doesn't support Active Directory management yet) and then to add that user as a co-administrator in settings > administrators.
You can create a user through Powershell, and assign much more granular permissions, but while you're working your way around things it is probably easier to stay within the portal.
There is no significant difference between a user created through the old portal and one created via AzureRm commands.
I just encountered the same problem and while the information posted here was helpful it didn't solve the problem completely.
The key insight I needed was that in order to use Azure Cmdlets one has to configure a 'Run as Account'. (See https://learn.microsoft.com/en-us/azure/automation/automation-sec-configure-azure-runas-account)
It can be set up under Account Settings section of the azure automation account.
Once you have the 'Run as Account' you can use the method proposed by BlackSpy to log in. Namely:
# Get the connection
$servicePrincipalConnection = Get-AutomationConnection -Name AzureRunAsConnection
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
Hope this might help someone.
The official advice is to use a ServicePrincipal for automation - you can either use Secret or Certificate credentials with a service principal, and certificates work the best.
It is still possible to use a work or school account for automated login (Login with just -Credential), but this requires that your organization does not require two-factor authentication. It is unfortunately not possible to use a Microsoft Account for this - microsoft accounts require user interaction for any login.

Add-AzureAccount -credential not working as I'd hoped

4 days ago (on 4th August 2014) there was a new release of Azure Powershell that included a new -Credential parameter on the Add-AzureAccount cmdlet. I'm trying to use it but I'm clearly doing something wrong.
First I store my password in a file:
read-host -assecurestring | convertfrom-securestring | out-file C:\temp\securestring.txt
Then try and use it in Add-AzureAccount
$password = cat C:\temp\securestring.txt | convertto-securestring
$username = "dhdom1\jamiet" #yes, this is the correct username
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
Add-AzureAccount -credential $mycred
The call to Add-AzureAccount fails:
Add-AzureAccount : user_realm_discovery_failed: User realm discovery
failed: The remote server returned an error: (404) Not Found.
I know that "dhdom1\jamiet" is the correct account. Anyone any idea why this might be failing? TIA
You should use the organizational account you use to log in to the Azure Portal with. So, it might look like jamiet#yourorganizationalaccountname.com, or something like that.
open azure powershell window
type Add-AzureAccount then enter
a login screen will be popuped to him then enter this credential outlook
by this, this credentials are stored in this PowerShell window, then run all other scripts from this specific window.