Azure Powershell to stop VM's in a subscription - powershell

I am new to Powershell, and to be specific entirely new to Azure Powershell. I need to create a powershell script to switch off all the VM's found on a subscription. I guess this needs to be done with the help of management certificate. But not sure where to start. I just done some simple lines of code to list all VM's as shown below:
Add-AzureAccount -Environment "AzureCloud"
$subscription = "my-sub-scri-ption"
Select-AzureSubscription -Current "SubName"
Set-AzureSubscription -SubscriptionName "SubName"
Get-AzureVM -ServiceName "VM1"
The output recieved is "Get-AzureVM : Value cannot be null.
Parameter name: subscriptionId".
Can someone please help me in this regard?
**EDIT:**
The powershell script which I am using is given below:
Add-AzureAccount -Environment "AzureCloud"
Set-AzureSubscription -SubscriptionName "My Subs"
$serviceName = "Service01"
$vmName = "Service01"
Get-AzureVM | Stop-AzureVM -Force
Though while running it shows script execution is successful, I can see still that vm is powered on. Please note that the serviceName and vmName is same in my case. Anything wrong here in my code?
**Re-Edit**
Executed code:
Add-AzureAccount -Environment "AzureCloud"
Set-AzureSubscription -SubscriptionName "My Subs"
$serviceName = "Service01"
$vmName = "Service01"
Get-AzureVM
Error for the above code:
Get-AzureVM : Value cannot be null.
Parameter name: subscriptionId
At D:\TC_PS\Untitled1.ps1:5 char:1
+ Get-AzureVM
+ ~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ArgumentNullException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand

You can start from here: Getting Started with Windows Azure PowerShell
Then you can simply run Get-AzureVM that will return all the virtual machines for every cloud service.
To stop a VM: Stop-AzureVM -ServiceName xxx -Name vm-test-01
To stop all the VMs in the subscription simply run: Get-AzureVM | Stop-AzureVM -Force
The -Force switch is necessary to stop the last virtual machine of the cloud service, otherwise the system would throw an error when trying to stop the last VM in the service, to avoid drop all the resources of your published app.
If you don't specify the -StayProvisioned switch, the virtual machine will be deallocated. This is the default behavior of Stop-AzureVM.

Related

Get-AzureStorageKey Error on Azure Automation

I'm configuring a Azure Automation Runbook with a "Classic RunAs Connection".
After I select the Azure Subscription with this connection, I'm getting the storage key for one of my storage accounts, but the problem is that sometimes it works and sometimes it doesn't. Here is what I'm doing:
$ConnectionAssetName = "AzureClassicRunAsConnection"
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
$CertificateAssetName = $Conn.CertificateAssetName
$Cert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
$storageAccountKey = Get-AzureStorageKey -StorageAccountName "MyStorageAccountName"
The transient error that occurs is:
Get-AzureStorageKey : An error occurred while sending the request.
At line:38 char:26
... eAccountKey = Get-AzureStorageKey -StorageAccountName "MyStorageAccountName"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : CloseError: (:) [Get-AzureStorageKey], HttpRequestException
FullyQualifiedErrorId :
Microsoft.WindowsAzure.Commands.ServiceManagement.StorageServices.GetAzureStorageKeyCommand
It works most of the time, but sometimes this exception is thrown.
Can somebody help me?
Thanks!
After some unsucessful testing, I decided to store the StorageKey inside an encrypted variable.
I know that this is not the best solution, but I didn't find the problem.
The original solution worked most of the time, but the exception thrown when the error occurs, didn't help me to find it.
You need to use a RunAs connection - the ClassicRunAsConnections are for RDFE, the KeyVault cmdlets use your AzureRm credentials. The RunAs credentials provide you with a Service Principal, and you need to give that service principal access to your KeyVault in KeyVault configuration

AzureRM Automation PSWorkflow Runbook - error while attaching NIC to subnet

I'm trying to create a parallel Workflow script but facing some challenges while attaching NIC to existing Subnet. I'm getting the following error.
Microsoft.PowerShell.Utility\Write-Error : Cannot validate argument on
parameter 'SubnetId'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
Following is my Workflow script which creates VNet, Subnet, NSG, PIP and tries to create NIC from AzureRM automation Runbook.
"Get Virtual Network Information" $gvnet = Get-AzureRmVirtualNetwork
-Name $VNetName -ResourceGroupName $SharedResourcesRGName
$nic = New-AzureRmNetworkInterface -Name "$VMName-NIC"
-ResourceGroupName $VMName -Location $VMLocation `
        -SubnetId $gvnet.Subnets[0].ID -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $gnsg.Id -Force
How do I get the value of Subnet in AzureRM Workflow runbook
Gulab Pasha

New-AzureRmResourceGroup command not working in powershell

I have logged into my Azure account and selected the appropriate subscription.
But it always gives the same error
PS C:\WINDOWS\system32> New-AzureRmResourceGroup -Name "AzureMediaServicesSample" -Location "East US"
New-AzureRmResourceGroup : Run Login-AzureRmAccount to login.
At line:1 char:1
+ New-AzureRmResourceGroup -Name "AzureMediaServicesSample" -Location " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-AzureRmResourceGroup], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzur
eResourceGroupCmdlet
I have selected the subscription too using select-azuresubscription
select-azuresubscription is used for ASM mode.
For ARM mode, you need use Get-AzureRmSubscription -SubscriptionName "your sub" | Select-AzureRmSubscription to select your subscription.
More information please refer to this example.
Update:
You could use the following cmdlet to check Azure PowerShell version.
Get-Module -ListAvailable -Name Azure -Refresh
You could install the latest PowerShell from the link.
I had the same problem and I solved it by changing the environment setting from Bash to Powershell in the upper left corner of the Cloud Shell Window.

Azure PowerShell automation "no default subscritpion has been designated"

I am getting the following error. I am in fact setting the default subscription name.
4/27/2015 10:28:28 AM, Error: Get-AzureVM : No default subscription
has been designated. Use Select-AzureSubscription -Default
to set the default subscription. At test:9 char:9
+
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ApplicationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand
Here is my code:
workflow test
{
# Initial set up
$Cred = Get-AutomationPSCredential -Name "******"
Add-AzureAccount -Credential $Cred
Select-AzureSubscription -Default -SubscriptionName 'Beebunny'
$vmName = "MyMachineName"
Get-AzureVM -servicename $vmName
Write-output "All done."
}
If I try Select-AzureSubscription -Default 'SubscriptionName' it throws an error saying the syntax is invalid.
Edit: I have also tried Select-AzureSubscription -SubscriptionName 'SubscriptionName' without the Default flag.
Funny thing is that if I run this in AzurePS directly from Windows, it runs just fine. I am about 95% sure this is an Azure bug but wanted to get a second opinion first.
What version of the Azure module do you have loaded? Are you using the default module provided by the Automation service? Also, have you imported any other modules to this subscription?
Try creating a clean runbook with the following code, replacing the credential and subscription with the proper names. Can you get the credential and authenticate successfully?
workflow Test-GetVM
{
$Cred = Get-AutomationPSCredential -Name 'AdAzureCred'
if(!$Cred) {
Throw "Could not find an Automation Credential Asset named. Make sure you have created one in this Automation Account."
}
$Account = Add-AzureAccount -Credential $Cred
if(!$Account) {
Throw "Could not authenticate to Azure. Make sure the user name and password are correct."
}
Select-AzureSubscription -SubscriptionName "Visual Studio Ultimate with MSDN"
Get-AzureVM
}
UPDATE: Do you have the Resource Manager module loaded to the subscription as well?
I had the same problem and the solution was execute Add-AzureAccount, do the login process requested and once done all was working.

Deploying web role in Azure throws exception on CurrentAccountStorageName

I want to deploy a web role to Azure using the PowerShell CmdLets.
My script is as follows:
$subscription = "<name-of-subscription>"
$service = "<name-of-cloudservice>"
$slot = "staging"
$package = "path\to\package.cspkg"
$configuration = path\to\config.cscfg"
$deploymentLabel = "Deploy to $service"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\Azure.psd1"
Import-AzurePublishSettingsFile "C:\path-to.publishsettings"
Set-AzureSubscription -CurrentStorageAccount $service -SubscriptionName $subscription
# some more stuff to check whether to upgrade or to create ...
Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force
When I execute this it throws an error:
Exception: The subscription named <name-of-subscription> already exists.
I figured that since I'm importing my publishsettings-file already I could get rid of Set-AzureSubscription. However, once I do that I get the next error:
Exception: CurrentStorageAccountName is not set.
Use Set-AzureSubscription subname -CurrentStorageAccountName storageaccount to set it.
This is the line that gave me the error in the first place, so I'm not sure how I need to set the storageaccountname without causing an error.
I also ran a little test:
Import-AzurePublishSettingsFile "C:\path-to.publishsettings"
Get-AzureSubscription | Format-Table
Once I do this I get the following output (reformatted):
SubscriptionName: <name-of-subscription>
SubscriptionId: 123456789-123...
ServiceEndpoint: https://man....
ActiveDirectoryEndpoint:
ActiveDirectoryTenantId:
IsDefault: True
Certificate [Subject]
CurrentStorageAccountName
CurrentCloudStorageAccount
ActiveDirectoryUserId
As you can see, the CurrentStorageAccountName is empty, but I don't know how I can set it to a correct value.
I looked up some other scripts, but they all seem to be having this sequence of importing, then setting. Any idea why this is not working and how to solve it?
You are trying to set CurrentStorageAccount to the name of your cloudservice, but you should be setting it to the name of your blob storage account. Get the list of you storage accounts
PS U:\>Get-AzureStorageAccount |select StorageAccountName
StorageAccountName
------------------
portalvhdsgsomething
storage1
storage2
storage3
then run your previously failing line but with the name of your storage account ie.
Set-AzureSubscription -CurrentStorageAccount storage2 -SubscriptionName $subscription
You can confirm your changes with
PS U:\>Get-AzureSubscription | select CurrentStorageAccount
CurrentStorageAccount : storage2
You need to use -CurrentStorageAccountName as the parameter of Set-AzureSubscription.
For Set-AzureSubscription the MSDN doc shows the -SubscriptionName parameter as parameter 1, not as named. The error message's suggested fix even implied that you needed to do Set-AzureSubscription <service> -CurrentStorageAccount <storage solution> Perhaps simply moving that will solve it?
Set-AzureSubscription -SubscriptionName $subscription -CurrentStorageAccount $service
Reference: http://msdn.microsoft.com/en-us/library/dn495189.aspx
I have found out the reason. It appears that you cannot include the subscription name as a named parameter. Changing this line:
Set-AzureSubscription -CurrentStorageAccount $service -SubscriptionName $subscription
to this line did the trick
Set-AzureSubscription $subscription -CurrentStorageAccount $service