Powershell cmdlet to gracefully shutdown azure virtual machine - azure

I am having questions around the "Stop-AzureRmVm" PowerShell cmdlet. Does the cmdlet power crash the virtual machines? I have few SharePoint and SQL servers used in our non-production environment. I have powershell scripts that do a scheduled stop and start of these virtual machines.
I am worried if the "Stop-AzureRmVm" PowerShell cmdlet power crashes the virtual machines, as I need the servers to gracefully shutdown.
OR do we have any PowerShell cmdlet that gracefully shuts down the Azure virtual machine?

As long as you are not sending the -force parameter, Azure will attempt to gracefully shutdown the guest OS before stopping. If that doesn't work, the -force parameter is akin to "pulling the plug".

Dont worry, the command Stop-AzureRmVm will gracefully shut down the VM.
If you catch the request of the Stop-AzureRmVm and the Stop option of the VM in the portal, you will find essentially they all call the Virtual Machines - Deallocate REST API, it means if you use the powershell command, it is no difference with that in the portal.

Sorry to revive an old question, but Ken W's accepted answer here is not accurate. The -Force parameter only prevents a Yes/No prompt when running the cmdlet (this is useful for when running in an automated script which cannot accept user input). Either way, running Stop-AzureRmVm will always attempt a graceful shutdown.
The newer 'Az' version of this cmdlet (Stop-AzVM) does have a -SkipShutdown option which will skip any attempt at a graceful shutdown, and will immediately deallocate the VM. More details can be found in the following link:
https://learn.microsoft.com/en-us/powershell/module/az.compute/stop-azvm

Related

Is there a way to create a PowerShell script to stop the virtual machine automatically during the idle time of the virtual machine in azure?

Please suggest me the powershell script to stop a virtual machine IN AZURE when it attains given maximum idle time and after that it must automatically starts running when the user logs into that virtual machine?
One way to accomplish this is to create a scheduled task inside the VM. That scheduled task will trigger when the machine is idle. The script the task will run is:
Stop-AzVM -Name <VM name> -ResourceGroupName <RG Name> -Force
As for the second part of starting when a user logs on, that is not possible. The VM will be off/de-allocated, there is nothing to log on to.
NOTE: the VM that has the scheduled task will also need the Azure Powershell modules installed on it and a system managed identity.

How to run a script on Azure VM from a remote machine

I'm looking for a way to run a script, on a single instance of a cloud service (which has several instances) from a remote machine.
I've tried DSC but that doesn't seem to support running the script only on one machine, as it would run it on all machines of the cloud service.
Note I'm using classic Azure cloud services.
Update: I specifically have an issue with Get-AzureVM which is part of the script example.
How do I get the instance VM which is part of my cloud service.
For instance I tried:
Get-AzureVM -ServiceName myCloudServiceName -Name instanceVMName
And that didn't return anything (I made sure to Add-AzureAccount first).
I’m assuming it returns nothing because Get-AzureVM cannot be used for cloud services, and only for VMs.
I’m able to get the instance by running
$dep = Get-AzureDeployment -ServiceName myCloudServiceName -Slot Production
$dep.RoleInstanceList[0]
Which returns role instance type which is different from the expected VM type.
Any ideas?
Powershell Remoting in Azure Cloud Services
As you are using a single instance the above should do the trick, you will need to create the user as part of a startup script, otherwise it will disappear each time it recreates the VM. It will not work if you every scale out to more than one instance of a cloud service.
You could use Custom Script extension for Windows virtual machines. It supports run on a single VM.
With the Custom Script extension for Windows, you can run PowerShell scripts on a remote VM without signing in to it. You can run the scripts after provisioning the VM, or at any time during the lifecycle of the VM without opening any additional ports. The most common use cases for running Custom Script extension include running, installing, and configuring additional software on the VM after it's provisioned.
More information please refer to this link.

Cannot run remote session on Azure Automation hybrid worker

I have a Powershell Azure Automation runbook that remotes into a machine to update some configuration. The runbook seems to work properly when run from Azure, but fails with an authentication error when run from a Hybrid Worker.
The whole reason for having the Hybrid Worker was so I could secure the PSRemoting ports to known hosts, so this is a bit of a bummer.
The main runbook is triggered via webhook, and that calls a child runbook using dot-notation, which calls...
$creds = Get-AutomationPSCredential -Name 'DeploymentCredentials'
$sessionOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
Invoke-Command -ConnectionUri "https://$($FQDN):5986" -Credential $creds -SessionOption $sessionOptions -ScriptBlock {
$h = hostname
Write-Output "Running on $h"
}
In this case, $FQDN is supplied as a parameter of course.
The error being reported is:
Connecting to remote server
my-server.australiaeast.cloudapp.azure.com failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
CategoryInfo : OpenError: (my-server.au...udapp.azure.com:String) [], PSRemotingTransportException
FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
I can manually execute the same code from ISE without issue from the hybrid worker so I know it's not a firewall issue, and I have the credentials writing to the output window so I know they are correct too.
I presume this is something to do with the fact the PowerShell function executes under the system account?
Thx
Answering my own question for posterity.
Altering the Hybrid Worker Group to run using credentials for a machine admin allowed the setup to work; where using the "Default" credentials (System account I believe) did not.
I think in Windows the System account is not allowed to connect to other machines/services so this may be why, but I'm guessing there.

Start VM, run exe, stop VM in azure automation

I want to start an exe that is located in a VM every day. The exe is 5 minutes long, so I want to use azure automation to start the vm, run the exe, and when it's finished, stop the vm.
I've looked at some resources on the web, and I can start the VM with :
Start-AzureVM -Name $VMName -ServiceName $ServiceName
I've seen in examples that people stop vm in other job at a certain time, but is it possible to start the vm, run an exe and stop the vm when the exe has terminated ?
You could start the VM via automation, and then fire off the exe from a Powershell script. When the exe exits you could call Stop-AzureVM / Stop-AzureRmVM
PowerShell Remoting
Yes, you can use a PowerShell Remoting session, which sits on top of Windows Remote Management (WinRM) to achieve this.
The high-level workflow for your Azure Automation Runbook would look something like:
Start-AzureVM ...
Invoke-Command ...
Stop-AzureVM ...
The Invoke-Command PowerShell command creates a PowerShell Remoting session (PSSession) to the Azure Virtual Machine, using the VM's public WinRM endpoint. The command will run synchronously by default, unless you use the -AsJob parameter to execute the command as a PowerShell Background Job, on the Runbook Worker. If you choose to invoke the remote command (your exe file) as a Background Job, then you can use the Wait-Job command to wait for its completion, before calling Stop-AzureVM.
IaaSv1 or IaaSv2?
Another major factor in your automation work, is considering whether you are using Azure Service Management (ASM) or Azure Resource Manager (ARM). Azure has two different APIs, and depending on how you created your VM, you will be using one or the other.
ASM = IaaSv1 (classic VMs)
ARM = IaaSv2
When you provision IaaS VMs in ASM, they must be a member of a "Cloud Service" container. Conversely, in ARM / IaaSv2, you can create VM instances as top-level members of your Azure subscription (account), with the caveat that all ARM-based cloud resources must be deployed into a "Resource Group."
ASM and ARM have entirely separate PowerShell modules. The ASM command is Start-AzureVM and the ARM equivalent is Start-AzureRmVM. Due to the inherent differences in the ASM and ARM architecture, these two commands also have different parameters. The ASM version requires that you specify the "Cloud Service" that the IaaS VM belongs to, whereas the ARM version requires that you specify the "Resource Group" that the VM belongs to.
For whoever may visit here, here is the example of Start VM, Run a script and stop VM.
https://github.com/shanjin14/AzureAutomation
In the RunPython.ps1 just need to put the full file path to the exe file
such as "C:\abc.exe"
Cheers. hope it helps

Powershell command to know duration of the running VM

Is there any PowerShell command to know the duration for which Azure VM has been running?
You should be able to use the Get-VM PowerShell cmdlet to see uptime.
Here are some other cmdlets you might be interested in when using Hyper-V
http://www.altaro.com/hyper-v/10-awesome-hyper-v-cmdlets/

Resources