Run PowerShell on AVD VMs Without Lots of Tooling

I was working with a customer that needed to change some settings on all the VMs in a host pool, and while they had Intune, it wasn’t all that easy to “make that change” with Intune
(I wasn’t any help at all… I have near zero Intune mojo!).

What we did was to leverage Azure, and the agent installed on the Azure-based AVD VMs. This allowed us to execute PowerShell scripts using Invoke-AzVMRunCommand. Looping through the VMs in a hostpool and running scripts is something I’ve been doing for quite some time, and thought I’d share for those times when you may be working in an environment without (say) Nerdio Manager or without Intune or other tool access.

What I did was create a PowerShell script on my local workstation called C:\MyScript.PS1, which contained the code we needed to run locally (and elevated) on each VM.

MyScript.PS1 was then executed on ever VM in the Host pool using the following code:

#change variables below to match your environment
$GovResourceGroup   = "YourResourcGroupName"
$GovSubscriptionID  = "11111111-1111-1111-1111-1111111111111”
$GovHostPool    = "YourHostPoolName"  

# I think modules needed: AZ, AZ.Compute, AZ,DesktopVirtualization, AZ,Accounts
# Install-Module -Name Az

# I run in Azure Gov... so need the Environment name!
Connect-AzAccount -EnvironmentName AzureUSGovernment 
Select-AzSubscription -SubscriptionId $GovSubscriptionID
$VMs = Get-AZWVDSessionHost -ResourceGroupName $GovResourceGroup -HostPoolName $GovHostPool

Foreach ($VM in $VMs) { 
  $DNSname = $"/")[1]
  $VMname = $DNSname.split(".")[0]
  Invoke-AzVMRunCommand -Name $VMname -ResourceGroupName $GovResourceGroup -CommandId 'RunPowerShellScript' -ScriptPath .\MyScript.PS1

The magic really happens in the Foreach loop, where the VM names from the HostPool are used to “Invoke” MyScript.PS1.

Hope you find this useful!

Leave a Reply

Your email address will not be published. Required fields are marked *