<# .SYNOPSIS Stages the PowerShell modules bundled with the agent payload: the modern gallery client (PSResourceGet), Archive and ThreadJob. The embedded PowerShell SDK ships only the core engine modules, so bundling these guarantees Install-PSResource / Compress-Archive / Start-ThreadJob on every endpoint regardless of what is installed there. Downloads pinned versions from the PowerShell Gallery (a NuGet v2 feed), caches the packages, and lays them out as Modules\\\… ready to copy next to the agent binary. Outputs the staged directory path. #> [CmdletBinding()] param( [string]$CacheDir ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot if (-not $CacheDir) { $CacheDir = Join-Path $repoRoot 'artifacts/cache' } $stage = Join-Path $CacheDir 'agent-modules' # Pinned: bump deliberately, never floating. $modules = @( @{ Name = 'Microsoft.PowerShell.PSResourceGet'; Version = '1.2.0' } @{ Name = 'Microsoft.PowerShell.Archive'; Version = '1.2.6' } @{ Name = 'Microsoft.PowerShell.ThreadJob'; Version = '2.2.0' } ) foreach ($module in $modules) { $target = Join-Path $stage "$($module.Name)/$($module.Version)" if (Test-Path (Join-Path $target "$($module.Name).psd1")) { continue } $nupkg = Join-Path $CacheDir "$($module.Name).$($module.Version).nupkg.zip" if (-not (Test-Path $nupkg)) { New-Item -ItemType Directory -Force (Split-Path $nupkg) | Out-Null $url = "https://www.powershellgallery.com/api/v2/package/$($module.Name)/$($module.Version)" Write-Host "Downloading $($module.Name) $($module.Version)" # WebClient: no progress-rendering overhead, follows the gallery redirect. $client = [System.Net.WebClient]::new() try { $client.DownloadFile($url, $nupkg) } finally { $client.Dispose() } } if (Test-Path $target) { Remove-Item $target -Recurse -Force } New-Item -ItemType Directory -Force $target | Out-Null Expand-Archive -Path $nupkg -DestinationPath $target -Force # Strip NuGet packaging metadata; what remains is the module layout. foreach ($junk in '_rels', 'package', '[Content_Types].xml') { Remove-Item (Join-Path $target $junk) -Recurse -Force -ErrorAction SilentlyContinue } Get-ChildItem $target -Filter '*.nuspec' | Remove-Item -Force if (-not (Test-Path (Join-Path $target "$($module.Name).psd1"))) { throw "Module manifest missing after extracting $($module.Name) $($module.Version)." } Write-Host "Staged $($module.Name) $($module.Version)" } $stage