- 1 year ago
How to add a powershell script/command as userdata for Windows VMs in Azure
To add a PowerShell script or command as userdata for Windows virtual machines (VMs) in Azure, you can use the Azure PowerShell module or Azure CLI. Here's how you can do it using Azure PowerShell:
Install Azure PowerShell: If you haven't already, install the Azure PowerShell module on your local machine. You can find installation instructions in the Azure PowerShell documentation.
Create a PowerShell script or command: Prepare your PowerShell script or command that you want to run as userdata. Save it to a local file or define it as a string in your script.
Connect to Azure: Open PowerShell and sign in to your Azure account using the
Connect-AzAccount
command. Provide your credentials when prompted.Create a VM with userdata: Use the
New-AzVM
cmdlet to create a virtual machine and specify the userdata using the-CustomData
parameter. Here's an example:
powershell$userdata = @"
<powershell>
# Your PowerShell script or command goes here
# For example, run a command:
Get-Process
# Or execute a script:
Invoke-Command -ScriptBlock {
# Your script logic goes here
}
</powershell>
"@
$vmParams = @{
ResourceGroupName = "YourResourceGroup"
Name = "YourVMName"
Location = "YourLocation"
Image = (Get-AzVMImageOffer -Location "YourLocation" -PublisherName "MicrosoftWindowsServer" -Skus "2019-Datacenter" -Version "latest").ImageReference
Size = "Standard_D2s_v3"
CustomData = $userdata
# Add other VM configuration parameters as needed
}
New-AzVM @vmParams
In this example, the $userdata
variable contains the PowerShell script or command wrapped in <powershell>
tags. Modify the script or command inside the <powershell>
section as per your requirements.
- Execute the script: Run the PowerShell script to create the virtual machine with the specified userdata. The script will execute the userdata as part of the VM provisioning process.
When the virtual machine is created, Azure will execute the provided userdata during the initial boot sequence of the VM. The script or command specified in the userdata will run within the VM, allowing you to perform custom configuration or execute specific actions.
Make sure to adapt the example code to your specific resource group, VM name, location, and other configuration parameters.
Alternatively, you can achieve the same using the Azure CLI by utilizing the az vm create
command with the --custom-data
parameter to specify the userdata.
Remember to ensure that your Azure account has the necessary permissions to create and manage virtual machines in the desired resource group.