iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔧

How to Automate Batch Installation of Visual Studio Workloads and Components with PowerShell

に公開

Solution

This article introduces a method to automatically batch-install specific Visual Studio workloads and components using a PowerShell script. The script checks combinations of multiple products and channels, and if a corresponding installation path is found, it installs the required workloads together. Since administrative privileges are required, please run it with the appropriate permissions.

# Set to stop immediately if an error occurs
$ErrorActionPreference = "Stop"

# Administrator privilege check
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "This script must be run with administrator privileges. Please run PowerShell as an administrator and execute the script again."
    exit 1
}

# Define Visual Studio Installer paths as variables
$vsInstallerDir = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
$vswhereExe = Join-Path $vsInstallerDir "vswhere.exe"
$vsInstallerExe = Join-Path $vsInstallerDir "vs_installer.exe"
$productIds = @(
    "Microsoft.VisualStudio.Product.Enterprise",
    "Microsoft.VisualStudio.Product.Professional",
    "Microsoft.VisualStudio.Product.Community"
)
$channelIds = @(
    "VisualStudio.17.Preview",
    "VisualStudio.17.Release"
)
$workloadIds = @(
    "Microsoft.VisualStudio.Workload.CoreEditor",
    "Microsoft.VisualStudio.Workload.NetWeb",
    "Microsoft.VisualStudio.Workload.Azure",
    "Microsoft.VisualStudio.Workload.ManagedDesktop",
    "Microsoft.VisualStudio.Workload.Universal",
    "Microsoft.VisualStudio.Workload.Data",
    "Microsoft.VisualStudio.Workload.DataScience",
    "Microsoft.VisualStudio.Workload.VisualStudioExtension",
    "Microsoft.VisualStudio.Workload.Office",
    "Microsoft.Net.Component.4.8.1.SDK",
    "Microsoft.Net.Component.4.8.1.TargetingPack"
)

# Create combinations of products and channels
$combinations = foreach ($productId in $productIds) {
    foreach ($channelId in $channelIds) {
        [PSCustomObject]@{
            ProductId = $productId
            ChannelId = $channelId
        }
    }
}

# Get the installation path and identify installable products and channels
$missingWorkloads = @()
foreach ($combination in $combinations) {
    $productId = $combination.ProductId
    $channelId = $combination.ChannelId

    $installationPath = & $vswhereExe -format json -prerelease |
        ConvertFrom-Json |
        Where-Object { $_.productId -eq $productId -and $_.channelId -eq $channelId } |
        Select-Object -First 1 |
        Select-Object -ExpandProperty installationPath -ErrorAction SilentlyContinue

    if ($installationPath) {
        # Check for workloads that are not installed
        foreach ($workloadId in $workloadIds) {
            $isExists = & $vswhereExe `
                -products $productId `
                -requires $workloadId `
                -format json `
                -prerelease |
                ConvertFrom-Json |
                Where-Object { $_.channelId -eq $channelId } |
                Measure-Object |
                ForEach-Object { $_.Count -gt 0 }

            if ($isExists -eq $false) {
                Write-Host "Workload '$workloadId' is not installed." -ForegroundColor Yellow
                $missingWorkloads += $workloadId
            }
            else {
                Write-Host "Workload '$workloadId' is already installed."
            }
        }

        # If there are uninstalled workloads, install them in batch
        if ($missingWorkloads.Count -gt 0) {
            Write-Host "Installing the following workloads: $($missingWorkloads -join ', ')" -ForegroundColor Cyan

            # Add workloads in batch using Start-Process
            # Important: Reason for using Start-Process
            # To resolve the issue where the script doesn't exit automatically and waits for Enter key input after vs_installer.exe runs
            $process = Start-Process `
                -FilePath $vsInstallerExe `
                -ArgumentList `
                    "modify", `
                    "--productId", $productId, `
                    "--channelId", $channelId, `
                    "--add", ($missingWorkloads -join " --add "), `
                    "--includeRecommended", `
                    "--quiet", `
                    "--norestart" `
                -NoNewWindow `
                -PassThru `
                -Wait

            # Check the process exit code and report errors
            if ($process.ExitCode -ne 0) {
                Write-Error "Failed to modify installation for channel $channelId. Exit code: $($process.ExitCode)"
            }
            else {
                Write-Host "Successfully modified workload installation." -ForegroundColor Cyan
            }
        }
        else {
            Write-Host "All workloads are already installed."
        }
    }
}

Explanation

This PowerShell script is designed to install specific Visual Studio workloads and components following this flow:

  1. Administrator privilege confirmation:
    Running the script requires administrative privileges; if the user is not an administrator, it displays an error message and exits.

  2. Visual Studio Installer path settings:
    It sets the paths for vswhere.exe and vs_installer.exe, targeting Enterprise, Professional, and Community editions across various channels (Preview and Release).

  3. Retrieving Visual Studio installation paths:
    It uses vswhere.exe to retrieve the installation path for Visual Studio matching the specified Product ID and Channel ID.

  4. Checking and installing workloads and components:
    For multiple product and channel combinations, it uses vswhere.exe to check for installed workloads or components. If any are missing, it performs an automatic batch installation using vs_installer.exe.

  5. Process management:
    It manages the post-installation process using Start-Process and appropriately reports errors by checking the exit code.

Additional Information

This script is useful when you want to automate the customization or reinstallation of Visual Studio. It is particularly effective when setting up the same environment for multiple developers or using it in CI/CD environments.

Please remember to run PowerShell as an administrator, as administrative privileges are required. Also, vswhere.exe and vs_installer.exe are official Microsoft tools included in the Visual Studio installation directory.

Discussion