Hope you are doing good!
Basically to answer your question , we should use Invoke command to run script in multiple VMs
Below is a PowerShell script that iterates through VMs in multiple subscriptions and adds the workspace ID and key:
# Define your workspace ID and key
$workspaceId = "<Your workspace Id>"
$workspaceKey = "<Your workspace Key>"
# List your Azure subscriptions
$subscriptions = Get-AzSubscription
# Loop through each subscription
foreach ($subscription in $subscriptions) {
# Set the current subscription context
Set-AzContext -Subscription $subscription.Id
# Get all VMs in the current subscription
$vms = Get-AzVM
# Loop through each VM and add the workspace
foreach ($vm in $vms) {
# Add the workspace to the VM using the script
$script = @"
$mma = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg'
$mma.AddCloudWorkspace("$workspaceId", "$workspaceKey")
$mma.ReloadConfiguration()
"@
$result = Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -ScriptInline $script -Verbose
Write-Host "Added workspace to $($vm.Name) in $($subscription.Name)"
}
}
Write-Host "Workspace ID and Key added to all VMs in all subscriptions."
Replace <Your workspace Id> and <Your workspace Key> with your actual workspace ID and key.
Important Notes:
- Ensure that the Azure PowerShell module is installed and up to date on your local machine.
- Make sure you are logged in to Azure using
az loginwith an account that has the necessary permissions to access the VMs and modify them. - The script iterates through all VMs in all subscriptions, so be cautious when running it in a production environment.
- This script uses the
Invoke-AzVMRunCommandcmdlet to run the script on the VMs. Ensure that the VM agent is installed and running on the VMs for this to work.