Hello PJ,
Thank you for your question and for reaching out with your question today.
Certainly! Below is an example PowerShell script that demonstrates how to loop through multiple Azure virtual machines, check if the Azure DevOps agent is missing, and install it if necessary:
# Install Azure PowerShell module if not already installed
if (-not (Get-Module -Name Az -ListAvailable)) {
Install-Module -Name Az -AllowClobber -Force -Scope CurrentUser
}
# Connect to Azure
Connect-AzAccount
# Set the target resource group and Azure DevOps organization
$resourceGroupName = "YourResourceGroupName"
$devOpsOrganization = "YourDevOpsOrganization"
# Get all Azure virtual machines in the specified resource group
$vms = Get-AzVM -ResourceGroupName $resourceGroupName
# Loop through each virtual machine
foreach ($vm in $vms) {
$vmName = $vm.Name
$vmStatus = $vm.PowerState
# Check if the virtual machine is running
if ($vmStatus -eq "VM running") {
# Check if Azure DevOps agent is installed on the virtual machine
$agentInstalled = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -Name $vmName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\path\to\check-agent.ps1' | Out-String
# If the agent is not installed, install it
if ($agentInstalled -notmatch "Azure Pipelines Agent") {
Write-Host "Azure DevOps agent is missing on VM '$vmName'. Installing..."
# Run command to install Azure DevOps agent on the virtual machine
Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -Name $vmName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\path\to\install-agent.ps1'
Write-Host "Azure DevOps agent installed on VM '$vmName'."
}
else {
Write-Host "Azure DevOps agent is already installed on VM '$vmName'."
}
}
else {
Write-Host "Virtual machine '$vmName' is not running."
}
}
In the script:
- Make sure you have the Azure PowerShell module installed. If not, the script will install it using
Install-Module
. - Replace
"YourResourceGroupName"
with the name of your target resource group. - Replace
"YourDevOpsOrganization"
with the name of your Azure DevOps organization. - Modify the paths in the
Invoke-AzVMRunCommand
commands to reference your own PowerShell scripts (check-agent.ps1
andinstall-agent.ps1
) that handle checking and installing the Azure DevOps agent. - The script uses
Invoke-AzVMRunCommand
to execute commands remotely on each virtual machine. Make sure you have the necessary permissions and network connectivity for running commands on the VMs. - Customize the output and any additional logic as per your requirements.
Remember to replace the placeholders and customize the script according to your environment and specific needs.
I used AI provided by ChatGPT to formulate part of this response. I have verified that the information is accurate before sharing it with you.
If the reply was helpful, please don’t forget to upvote or accept as answer.