Get-AzSubscription won't show my subscription - azure

I have a subscription I want to pause/resume with a PowerShell script (Azure Analysis Services). I use this exact same script to pause my Embedded Capacity and that works fine, but when I run my script for my new subscription it wont work. This is the script I use:
$userPassword = "myappsecret"
$userPassword2 = ConvertTo-SecureString -String $userPassword -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "appid", $userPassword2
Connect-AzAccount -ServicePrincipal -TenantId "tenantid" -Credential $Credential
Select-AzSubscription -SubscriptionId "subscriptionname here"
Get-AzPowerBIEmbeddedCapacity -ResourceGroupName "groupnamehere" -Name "namehere"
Suspend-AzPowerBIEmbeddedCapacity -Name "namehere" -ResourceGroupName "groupnamehere" -PassThru
To check why this won't work I tried to simply use Get-AzSubscription to see if something was wrong and it wont show any subscription.
If I try the same for my Embedded Capacity it works just fine.
What could be wrong?

To get the list of all Azure Ad subscriptions by using Get-AzSubscription, make sure that you have owner/admin role.
You can make use of the below command to get Azure Ad subscriptions for a specific tenant:
Make sure to connect-azaccount with Administrator details.
Get-AzSubscription -TenantId "your_tenant_id"
Get-AzContext command list the information of the Azure Subscription that is currently selected.
To use a specific subscription, you can make use of below command:
Get-AzSubscription -SubscriptionId "xxxx-xxxx-xxxx-xxxx" -TenantId "yyyy-yyyy-yyyy-yyyy" | Set-AzContext
Or please modify your code by adding the below snippet:
$subscriptionId = 'Your_Subscription_ID';
Select-AzSubscription -SubscriptionId $subscriptionId
You can check the Subscription Id via Azure Portal too.
Reference:
Get-AzSubscription (Az.Accounts) | Microsoft Docs

Related

Powershell Script to download Azure recommendations

Login-AzAccount
$subs= az account list --query '[*].id'
Get-AzAdvisorRecommendation list --subscription $subs
I need to download the list of Azure recommendations on a tenant which will be having multiple subscriptions using Powershell script
Get-AzAdvisorRecommendation list --subscription $subs
Instead of --subscription you need to pass -subscription as a parameter to Get-AzAdvisorRecommendation cmdlet.
As per the Azure PowerShell cmdlet documentation, The Cmdlet Get-AzAdvisorRecommendation doesnt have any flag -subscription as parameter.
You can use this below script to pull the azure advisor recommendations for all subscriptions under a particular tenant.
$list=#()
$sub=get-azsubscription
Write-Output $sub
foreach( $item in $sub){
Set-AzContext -Subscription $item.Id -Tenant $item.TenantId -Force
$rg=Get-AzResourceGroup
foreach($r in $rg){
$list+=Get-AzAdvisorRecommendation -ResourceGroupName $r.ResourceGroupName
}
}
$list | Export-Csv C:\Users\list.csv
Here is the sample output for reference:
While testing the above script in our local environment, we have passed a single subscription to the cmdlet Get-azsubscription using the -subscriptionId flag.
Using this updated script, I can download the recommendations as well, thanks Venkatesh for your inputs.
Login-AzAccount
$result= 'C:\Users\new.csv'
$list=#()
$subs=get-AzSubscription
foreach( $sub in $subs){
Set-AzContext -Subscription $sub.Id -Force
$list+=Get-AzAdvisorRecommendation | Select-Object category, Impact, #{Name="SubscriptionName"; Expression={$sub.name}}, #{Name="SubscriptionID";
Expression={$sub.Id}}, #{Name="Recommendation"; Expression=$_.ShortDescription.Problem}}, ImpactedField, ImpactedValue,RecommendationTypeId, LastUpdated, MetaData, SuppressionId, Name,
resourceid
}
$list | Export-Csv $result -NoTypeInformation

Azure Automation - Unable to get AzRoleAssignement

In order to automate some processes, I'm using Azure Automation with Owner rights for RunAsAccount.
$connection = Get-AutomationConnection -Name AzureRunAsConnection
while(!($connectionResult) -And ($logonAttempt -le 10))
{
$LogonAttempt++
# Logging in to Azure...
$connectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationId $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
Start-Sleep -Seconds 30
Write-Output $connectionResult
}
Get-AzRoleAssignment -ResourceGroupName $USERRGNAME -SignInName $USEREMAIL -verbos
An error is being thrown each time I execute the script:
Get-AzRoleAssignment: Cannot find principal using the specified options
Any idea to solve this issue?
Probably you need to give RunAsAccount with the Application permission Directory.Read.All of the Azure AD Graph(not Microsoft Graph, not Delegated permission). By default, RunAsAccount doesn't have the Azure AD permission.
You could read Joy's answer for more details.
This error is showing when there is no Role Assignment for name that is provided in the SignInName option.

Runbook automation fails but powershell cmd line works fine

I have the following powershell code for suspending azure d/w
$TenantId = "<>"
$SubscriptionId = "<>"
# Get the service principal credentials connected to the automation account.
$SPCredential = Get-AutomationPSCredential -Name "psvar"
# Login to Azure ($null is to prevent output, since Out-Null doesn't work in Azure)
Write-Output "Login to Azure using automation account 'psvar'."
$null = Login-AzureRmAccount -TenantId $TenantId -SubscriptionId $SubscriptionId -Credential $SPCredential
Write-Output "Login Status "
# Select the correct subscription
Write-Output "Selecting subscription '$($SubscriptionId)'."
$null = Select-AzureRmSubscription -SubscriptionID $SubscriptionId
$ResourceGroupName = '<>'
$ServerName = '<>'
$DatabaseName = '<>'
Write-Output "Suspending $($DatabaseName)..."
$null = Suspend-AzureRmSqlDatabase `
-ResourceGroupName $ResourceGroupName`
-DatabaseName $DatabaseName`
-ServerName $ServerName
Write-Output "Done"
Suspend azure rm sqldatabase works fine in PowerShell Azure Command line interface
But in runbook automation it fails with
Suspend-AzureRmSqlDatabase : Run Login-AzureRmAccount to login.
At line:33 char:9
+ $null = Suspend-AzureRmSqlDatabase `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Suspend-AzureRmSqlDatabase], PSInvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperation,Microsoft.Azure.Commands.Sql.DatabaseActivation.Cmdlet.SuspendAzureSqlDatabase
Any idea what could be wrong. Appreciate any pointers regarding this
I test your script, it works in the runbook.
Navigate to the automation account -> Credentials, make sure your user account name and password are correct.
If it still not work, you could try my solution here, it works.
For Azure Synapse analytics we need to use
Update-AzSynapseSqlPool -WorkspaceName <wsname>-Name <dbname> -Pause

Spinning up VM from Powershell with multiple admins

I have a script which spins up an Azure VM and specifies an admin username and password.
Is it possible to have the script setup a second admin? The reason for this is so that more than one user can be on the machine at the same time.
Do you have access to the vm with Invoke-Command?
If yes, might this helps: How to Manage Local Users and Groups using PowerShell
According to my research, two users can access Azure windows VM concurrently. A maximum of two concurrent connections are supported unless the server is configured as a Remote Desktop Services session host. Regarding how to add local user to Azure VM, you use the the VM Access extension in Azure PowerShell. For more details, please refer to the document
For example
Connect-AzAccount
$vm = Get-AzVM -ResourceGroupName jimtest -Name jimtest
$name = "jimtest1"
$password = "Pass***!"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycred= New-Object System.Management.Automation.PSCredential ($name, $secpasswd)
Set-AzVMAccessExtension -Credential $mycred -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Location $vm.Location -Name VMAccessAgent -TypeHandlerVersion "2.0"
You can use this PowerShell command below to add an admin account to your VM :
$adminName = "testadmin"
$passstr = "password123!"
$Password = ConvertTo-SecureString -String $passstr -AsPlainText -Force
New-LocalUser $adminName -Password $Password -FullName $adminName -Description "test admin account"
Add-LocalGroupMember -Group "Administrators" -Member $adminName
And you can use the Powershell command below to run your custom Powershell command on your Azure VMs(get started with azure powershell see here):
Connect-AzAccount
$vm = Get-AzVM -Name "<your vm name>" -ResourceGroupName "<your vm resource group>"
Invoke-AzVMRunCommand -VM $vm -CommandId 'RunPowerShellScript' -ScriptPath "<path of adding admin account command>"
so just save the first part command as a .ps1 file , and copy the path as value of you can add an local admin account to your VM.
Result :

Not able logout and do a non interactive login with Azure power shell

I have opened powershell and logged in to azure account by interactive login. Then i want to do a non-interactive login and i have the code for that. PFB is my code.
But when i use the below code, it is still taking the user from cache and also it is not throwing any error even if i give the wrong password also.
$subscriptionId="Subscription id here"
$tenantid="tenant id here"
$clientid="clinent id here" #appid
$password="password" #i have given the wrong password here
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $clientid, $securePassword
#Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId $tenantid -Subscription $subscriptionId
Add-AzureRmAccount -Credential $credential -TenantId $tenantID -ServicePrincipal -Subscription $subscriptionId
Here i want to logout from the Azure power shell and use non interactive login with the Service principal(Azure App). Can some one please help me.
To log out the account, you could use this command Remove-AzureRmAccount , or close the powershell and open a new one.
To use non interactive login with the Service principal, you could use the command below, the password is the secret of your AD app.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal

Resources