Code.ps1
# MrNetTek
# eddiejackson.net
# 7/15/2022
# free for public use
# free to claim as your own
$ErrorActionPreference = 'Continue'
Write-output "Getting Host Pool Information"
$HostPool = Get-AzResource -ResourceId $HostpoolID
$HostPoolResourceGroupName = $HostPool.ResourceGroupName
$HostPoolName = $Hostpool.Name
$Script = @"
`$ErrorActionPreference = 'Continue'
Try {
#Add specific user
#Add-LocalGroupMember -Group "Administrators" -Member "DOMAIN\AD_User_Account"
#Add specific group
Add-LocalGroupMember -Group "Administrators" -Member "DOMAIN\AD_Group_Name"
}
Catch {
Throw "Could not run command."
}
"@
$VM = get-azvm -VMName $azureVMName
$Script | Out-File ".\Command-$($vm.Name).ps1"
# Execute local script on remote VM
write-output "Execute script on remote VM"
$RunCommand = Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName "$AzureVMName" -CommandId 'RunPowerShellScript' -ScriptPath ".\Command-$($vm.Name).ps1"
# Check for errors
$errors = $RunCommand.Value | ? Code -eq 'ComponentStatus/StdErr/succeeded'
if ($errors.message) {
Throw "Error when running command. $($errors.message)"
}
Write-output "Output from RunCommand:"
$RunCommand.Value | ? Code -eq 'ComponentStatus/StdOut/succeeded' | select message -ExpandProperty message