Start / Shutdown specific VMs in Azure through an input file - azure

Need to shutdown specific VMs in my Azure subscription. Is there a way, I can make the ‘Get-AzureVM’ PowerShell cmdlet to read from an input file? We have too many VMs in our subscription. So specifying individual machine by name is tedious in our case.
Please advice.

I am assuming in the answer below that you are using ASM Azure portal, i.e. the older portal as you are using the ASM cmdlets.
If you want to start all VMs in your subscription then you can use:
Get-AzureVM | Start-AzureVM
If you want to start only specific VMs then you can use below script:
#Declaring the Dictionary object to store VM Names along with their Service names
$VMList = #{}
#Adding VMs to the VM List
#You can replace this section with reading from file and then populating your dictionary object
#Replace the VM Name and Service name with your environment data
$VMList.Add("VMName01", "ServiceName")
$VMList.Add("VMName02","ServiceName")
#Getting the VM object using Get-AzureVM and then starting the VMs
$VMList.Keys | % {Get-AzureVM -Name $_ -ServiceName $VMList.Item($_)} | Start-AzureVM

Related

How to get the details of the all Azure VM's with respective all Tag associated with it in excel sheet with the help of powershell?

How can I write a PowerShell script to get the report of all azure VMs in an excel spreadsheet, which includes the All tags associated with that, RG, and subscription?
You can implement the Powershell Script by following steps:
Install az modules in your local machine (Install-Module -Name 'Az' -allowclobber -scope currentuser)
Connect to your Azure subscription using this cmd (connect-Azaccount).
Use Get-AzVm Get-AzVM (Az.Compute) | Microsoft Docs to get the list of VM under the subscription and assign the output to a variable and by using the for each loop about Foreach - PowerShell | Microsoft Docs iterate the list in the variable and project the output to csv file using the export-csv.

Finding the last date of the vm using azure cli command

I have an account with Azure with different Resource Group and different virtual machine. I would like to know how I can determine which ones are unused. For example check the last date where the virtual machine was started or used by the user using azure cli command.
Please help me out with this...
Easiest would probably to look at the powerstate of a vm.
First list all the vm's and then run a query where you filter out those that are deallocated and belong to a specific resource group:
az vm list -d --query '[?powerState == `VM deallocated` && resourceGroup==`resource_group`]'
For more information on the queries look up 'JMESPath-query' on the Microsoft docs page. Hopefully this helps.
I would like to know how I can determine which ones are unused
Currently, there is no way to do that using cli.
check the last date where the virtual machine was started or used
We can get this information using PowerShell. which follows.
Get data information of deallocated VM using Get-AzVM -VMName xxxx - RgName xxx -Status
# To retrieve the date of VM was Deallocated.
$vmDeallocatedDate = Get-AzVM -VMName <Your VM name> -ResourceGroupName <Your ResourceGroup Name> -Status
$vmDeallocatedDate.Statuses[0].Time
List all the VM's and the timestamp of the action that triggered the Deallocation
Get-AzLog -Status Accepted -DetailedOutput | ?{$_.Authorization.Action -eq "Microsoft.Compute/virtualMachines/deallocate/action"} | fl ResourceId,EventTimestamp
References
Get-AzLog to get VM Deallocate status
Get-AzVM -status to get VM Deallocate status

List available VM SKUs for the azure policy "Allowed virtual machine SKUs"

$definition = Get-AzPolicyDefinition | Where-Object {$_.Properties.DisplayName -eq "Allowed virtual machine SKUs"}
New-AzPolicyAssignment -Name 'Test' -DisplayName 'Test' -Scope $ResourceGroup.ResourceID -PolicyDefinition $definition
Running this command will ask for 'listOfAllowedSKUs' for which SKUs i want to allow to be created in the specified resource group. I can find a list of them by going into the azure portal, finding policy and clicking assign policy, then selecting "Allowed virtual machine skus" and then going into parameters and looking at the names.
I can type in those names manually one by one when i get asked for it after running the command, but instead of opening the azure portal every time, i want to be able to list the available SKUs in powershell instead. I can't find anything online about getting a list of available SKUs in the console.
Is is possible to get a list of available SKUs to create?
Hello and welcome to Stack Overflow!
If you want to get the SKUs corresponding to a specific Location, Publisher and Offer, you may use the Get-AzVMImageSku cmdlet to get the VMImage SKUs by providing the Location, PublisherName and Offer as input parameters, and then construct the AllowedSkus object. For example:
$sku = Get-AzVMImageSku -Location "Central US" -PublisherName "Fabrikam" -Offer "LinuxServer"
$AllowedSkus = #{'listOfAllowedSKUs'=($sku.Skus)}
Else, to mimic the list of available SKUs as appearing in the portal, you may use the Get-AzVMSize cmdlet to get the available virtual machine sizes as follows:
$allsizes = Get-AzLocation | Get-AzVmSize | Select-Object -ExpandProperty Name | Sort-Object | Get-Unique
$AllowedSkus = #{'listOfAllowedSKUs'=($allsizes)}
This can finally be passed to the New-AzPolicyAssignment cmdlet using the -PolicyParameterObject option:
New-AzPolicyAssignment -Name '<policy assignment name>' -DisplayName '<display name>' -Scope $ResourceGroup.ResourceID -PolicyDefinition $definition -PolicyParameterObject $AllowedSkus
Other examples here. Hope this helps.
According to my test, if you want to know the available virtual machine SKUs in the subscription, you can use the following PowerShell command
Get-AzComputeResourceSku | where{$_.ResourceType.Equals('virtualMachines')}| fl
Its outputs contain parameter Restrictions. The parameter will tell us which SKU cannot be used.
For example
Giving one type of restriction : Zone Type for size Standard_A0 which means that under a particular subscription, Standard_A0 is not available to be created in West Europe region if placed in Availability Zones
Giving no Restrictions at the end, which means that VM Size : Standard_F8s can be created under this particular subscription in this region : West Europe without any restrcitions ( i.e : it can be created with Availaibility Zone and without Availaibility zone as well )
Giving two types of restrictions : Zone Type and Location Type, which means that VM Size of Standard_DS2_V2_Promo cannot be created in this particular subscription in this region : WestEurope at all.

Move a Microsoft Azure VM to a Different Subnet Within a vNet

Can't we Move a Microsoft Azure VM to a Different Subnet Within a vNet using the azure new portal or the azure classic portal ? if not possible through portal then how to do so ?then how to edit the properties of a VM after creation, like moving to a different subnet,, etc.,?
It is possible through the new portal. First I want to ask you if you're using a Classic VM or a Resource manager VM. If you're using the last one you can easily switch between subnets by changing the configuration settings.
go to your network interface > Ip configurations and click on the Nic name (see picture below)
A new tab will open and you can change the Subnet of the nic.
If your vm is a classic one, moving it to different vNet is very easy using azure powershell cmdlets. Here is the code-
$vmName = "xxxxx"
$srcServiceName = "xxxxx"
$newVNet = "xxxxx"
# export vm config file
$workingDir = (Get-Location).Path
$sourceVm = Get-AzureVM –ServiceName $srcServiceName –Name $vmName
$global:vmConfigurationPath = $workingDir + "\exportedVM.xml"
$sourceVm | Export-AzureVM -Path $vmConfigurationPath
# remove vm keeping the vhds and spin new vm using old configuration file but in a new vNet
Remove-azurevm –ServiceName $srcServiceName –Name $vmName
$vmConfig = Import-AzureVM -Path $vmConfigurationPath
New-AzureVM -ServiceName $srcServiceName -VMs $vmConfig -VNetName $newVNet -WaitForBoot
if not possible through portal then how to do so ?then how to edit the properties of a VM after creation, like moving to a different subnet,, etc.,?
It could be done with Powershell. In brief, it contains 3 steps:
Get the VM (NIC) configuration
Edit the VM (NIC) configuration
Update the edited configuration
Note: Moving VMs between different VNET is not supported. To move the VM to another VNET, the only solution for now is re-create the VM with the same vhd file.
Here is a good step-by-step guide:
How to change Subnet and Virtual Network for Azure Virtual Machines (ASM & ARM)

How do I create a powershell script to clone a vm in RM

I have created 2 Virtual Machines (VMs) using RM (Resource Manager) deployment method. How can I clone a VM using Azure PowerShell scripts?
You can follow the documentation guide here: https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-capture-image/
After you Open the Azure PowerShell and login to your Azure account.
You can find the subscriptions your Azure account has by using the command Get-AzureRmSubscription.
Next you will need to deallocate the resources used by this virtual machine.
Stop-AzureRmVM -ResourceGroupName YourResourceGroup -Name YourWindowsVM
Next you need to set the status of the virtual machine to Generalized. Note that you will need to do this because the generalization step above (sysprep) does not do it in a way that Azure can understand.
Set-AzureRmVm -ResourceGroupName YourResourceGroup -Name YourWindowsVM -Generalized
Next, Capture the virtual machine image to a destination storage container using this command.
Save-AzureRmVMImage -ResourceGroupName YourResourceGroup -VMName YourWindowsVM -DestinationContainerName YourImagesContainer -VHDNamePrefix YourTemplatePrefix -Path Yourlocalfilepath\Filename.json
The -Path variable is optional and can be used to save the JSON template locally. The -DestinationContainerName variable is the name of the container that you want to hold your images in. The URL of the image stored will be similar to https://YourStorageAccountName.blob.core.windows.net/system/Microsoft.Compute/Images/YourImagesContainer/YourTemplatePrefix-osDisk.xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.vhd. It will be created in the same storage account as that of the original virtual machine.
The Azure documentation offers a detailed guide to do this, so follow the instructions and in case of trouble, you can ask me!
BEWARE! When you sysprep your machine and make it generalized, you CANNOT UnDO this!!!
This means that you VM will stay stopped (deallocated) and you can create infinite cloned from this, but you cannot start this again, so make sure it is not in production :)

Resources