Run scripts in a Windows VM in Azure using action Run Commands - Azure Virtual Machines (2024)

  • Article

The Run Command feature uses the virtual machine (VM) agent to run PowerShell scripts within an Azure Windows VM. You can use these scripts for general machine or application management. They can help you to quickly diagnose and remediate VM access and network issues and get the VM back to a good state.

Benefits

You can access your virtual machines in multiple ways. Run Command can run scripts on your virtual machines remotely by using the VM agent. You use Run Command through the Azure portal, REST API, or PowerShell for Windows VMs.

This capability is useful in all scenarios where you want to run a script within a virtual machine. It's one of the only ways to troubleshoot and remediate a virtual machine that doesn't have the RDP or SSH port open because of improper network or administrative user configuration.

Prerequisites

Windows OS’ Supported

Windows OSx64
Windows 10Supported
Windows 11Supported
Windows Server 2008 SP2Supported
Windows Server 2008 R2Supported
Windows Server 2012Supported
Windows Server 2012 R2Supported
Windows Server 2016Supported
Windows Server 2016 CoreSupported
Windows Server 2019Supported
Windows Server 2019 CoreSupported
Windows Server 2022Supported
Windows Server 2022 CoreSupported

Restrictions

The following restrictions apply when you're using Run Command:

  • Output is limited to the last 4,096 bytes.
  • The minimum time to run a script is about 20 seconds.
  • Scripts run as System on Windows.
  • One script at a time can run.
  • Scripts that prompt for information (interactive mode) aren't supported.
  • You can't cancel a running script.
  • The maximum time a script can run is 90 minutes. After that, it will time out.
  • Outbound connectivity from the VM is required to return the results of the script.
  • It isn't recommended to run a script that will cause a stop or update of the VM Agent. This can let the extension in a Transitioning state, leading to a timeout.

Note

To function correctly, Run Command requires connectivity (port 443) to Azure public IP addresses. If the extension doesn't have access to these endpoints, the scripts might run successfully but not return the results. If you're blocking traffic on the virtual machine, you can use service tags to allow traffic to Azure public IP addresses by using the AzureCloud tag.

The Run Command feature doesn't work if the VM agent status is NOT READY. Check the agent status in the VM's properties in the Azure portal.

Available commands

This table shows the list of commands available for Windows VMs. You can use the RunPowerShellScript command to run any custom script that you want. When you're using the Azure CLI or PowerShell to run a command, the value that you provide for the --command-id or -CommandId parameter must be one of the following listed values. When you specify a value that isn't an available command, you receive this error:

The entity was not found in this Azure location

NameDescription
RunPowerShellScriptRuns a PowerShell script
DisableNLADisable Network Level Authentication
DisableWindowsUpdateDisable Windows Update Automatic Updates
EnableAdminAccountChecks if the local administrator account is disabled, and if so enables it.
EnableEMSEnableS EMS
EnableRemotePSConfigures the machine to enable remote PowerShell.
EnableWindowsUpdateEnable Windows Update Automatic Updates
IPConfigShows detailed information for the IP address, subnet mask, and default gateway for each adapter bound to TCP/IP.
RDPSettingsChecks registry settings and domain policy settings. Suggests policy actions if the machine is part of a domain or modifies the settings to default values.
ResetRDPCertRemoves the TLS/SSL certificate tied to the RDP listener and restores the RDP listener security to default. Use this script if you see any issues with the certificate.
SetRDPPortSets the default or user-specified port number for Remote Desktop connections. Enables firewall rules for inbound access to the port.

Azure CLI

The following example uses the az vm run-command command to run a shell script on an Azure Windows VM.

# script.ps1# param(# [string]$arg1,# [string]$arg2# )# Write-Host This is a sample script with parameters $arg1 and $arg2az vm run-command invoke --command-id RunPowerShellScript --name win-vm -g my-resource-group \ --scripts @script.ps1 --parameters "arg1=somefoo" "arg2=somebar"

Azure portal

Go to a VM in the Azure portal and select Run command from the left menu, under Operations. You see a list of the available commands to run on the VM.

Run scripts in a Windows VM in Azure using action Run Commands - Azure Virtual Machines (1)

Choose a command to run. Some of the commands might have optional or required input parameters. For those commands, the parameters are presented as text fields for you to provide the input values. For each command, you can view the script that's being run by expanding View script. RunPowerShellScript is different from the other commands, because it allows you to provide your own custom script.

Note

The built-in commands are not editable.

After you choose the command, select Run to run the script. After the script finishes, it returns the output and any errors in the output window. The following screenshot shows an example output from running the RDPSettings command.

Run scripts in a Windows VM in Azure using action Run Commands - Azure Virtual Machines (2)

PowerShell

The following example uses the Invoke-AzVMRunCommand cmdlet to run a PowerShell script on an Azure VM. The cmdlet expects the script referenced in the -ScriptPath parameter to be local to where the cmdlet is being run.

Invoke-AzVMRunCommand -ResourceGroupName '<myResourceGroup>' -Name '<myVMName>' -CommandId 'RunPowerShellScript' -ScriptPath '<pathToScript>' -Parameter @{"arg1" = "var1";"arg2" = "var2"}

Note

Parameter values can be string type only and the script is responsible for converting them to other types if needed.

Limiting access to Run Command

Listing the run commands or showing the details of a command requires the Microsoft.Compute/locations/runCommands/read permission on Subscription Level. The built-in Reader role and higher levels have this permission.

Running a command requires the Microsoft.Compute/virtualMachines/runCommands/action permission. The Virtual Machine Contributor role and higher levels have this permission.

You can use one of the built-in roles or create a custom role to use Run Command.

Action Run Command Windows troubleshooting

When troubleshooting action run command for Windows environments, refer to the RunCommandExtension log file typically located in the following directory: C:\WindowsAzure\Logs\Plugins\Microsoft.CPlat.Core.RunCommandWindows\<version>\RunCommandExtension.log for further details.

Known issues

  • Your Action Run Command Extension might fail to execute in your Windows environment if the command contains reserved characters. For example:

    If the & symbol is passed in the parameter of your command such as the below PowerShell script, it might fail.

    $paramm='abc&jj'Invoke-AzVMRunCommand -ResourceGroupName AzureCloudService1 -Name test -CommandId 'RunPowerShellScript' -ScriptPath C:\data\228332902\PostAppConfig.ps1 -Parameter @{"Prefix" = $paramm}

    Use the ^ character to escape the & in the argument, such as $paramm='abc^&jj'

  • The Run Command extension might also fail to execute if command to be executed contains "\n" in the path, as it will be treated as a new line. For example, C:\Windows\notepad.exe contains the \n in the file path. Consider replacing \n with \N in your path.

  • Ensure you don't have any custom setting in the registry key HKLM\SOFTWARE\Microsoft\Command Processor\AutoRun (detailed here). This could trigger during the RunCommand Extension install or enable phases and cause an error like 'XYZ is not recognized as an internal or external command, operable program or batch file'.

Action Run Command Removal

If needing to remove your action run command Windows extension, refer to the below steps for Azure PowerShell and CLI:

Replace rgname and vmname with your relevant resource group name and virtual machine name in the following removal examples.

 Invoke-AzVMRunCommand -ResourceGroupName 'rgname' -VMName 'vmname' -CommandId 'RemoveRunCommandWindowsExtension'
az vm run-command invoke --command-id RemoveRunCommandWindowsExtension --name vmname -g rgname

Note

When you apply a Run Command again, the extension will get installed automatically. You can use the extension removal command to troubleshoot any issues related to the extension.

Next steps

To learn about other ways to run scripts and commands remotely in your VM, see Run scripts in your Windows VM.

Run scripts in a Windows VM in Azure using action Run Commands - Azure Virtual Machines (2024)
Top Articles
The best 4K graphics card of 2024: top options for gamers and creatives
Accounting for SaaS: A Beginner's Guide
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Velia Krajcik

Last Updated:

Views: 5661

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.