Hello,
Welcome to Microsoft Q&A,
You can use the below PowerShell script to install the .Net 8 on all the VMs.
# Azure Login (if not already authenticated)
Connect-AzAccount
# Define variables
$resourceGroup = "YourResourceGroup"
$targetVMs = @("VM1", "VM2", "VM3") # List of specific VM names
# PowerShell script for remote execution
$remoteScript = @"
# Ensure winget is installed
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Write-Host "winget not found, skipping installation"
exit 1
}
# Install .NET 8.0
Write-Host "Installing .NET 8.0..."
winget install Microsoft.DotNet.Runtime.8 --silent --accept-package-agreements --accept-source-agreements
# Uninstall older .NET versions (1.x - 7.x)
Write-Host "Checking for older .NET versions..."
$installedVersions = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'Microsoft .NET%'" | Select-Object Name
foreach (\$version in \$installedVersions) {
if (\$version.Name -match 'Microsoft .NET (Core|Runtime) [1-7]\.') {
Write-Host "Uninstalling: \$version.Name"
\$app = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name='\$version.Name'"
\$app.Uninstall()
}
}
Write-Host "Update completed successfully!"
"@
# Iterate through only the specified VMs
foreach ($vmName in $targetVMs) {
$vm = Get-AzVM -ResourceGroupName $resourceGroup -Name $vmName -Status
if ($vm -eq $null) {
Write-Host "VM $vmName not found in resource group $resourceGroup. Skipping..."
continue
}
if ($vm.PowerState -eq "VM running") {
Write-Host "Processing VM: $vmName - Installing .NET 8 and removing old versions"
Invoke-AzVMRunCommand -ResourceGroupName $resourceGroup -Name $vmName -CommandId "RunPowerShellScript" -ScriptString $remoteScript
} else {
Write-Host "Skipping $vmName: VM is not running"
}
}
Please Upvote and Accept the answer if it helps!!