# After redeploy: remove all releases except current junction targets $ErrorActionPreference = 'Continue' $Root = 'E:\wwwroot' function Resolve-Link([string]$p) { if (-not (Test-Path $p)) { return $null } $i = Get-Item $p -Force if ($i.Target -and $i.Target.Count -gt 0) { return [string]$i.Target[0] } return $null } $keepAgent = Resolve-Link (Join-Path $Root 'agent\current') $keepAdmin = Resolve-Link (Join-Path $Root 'admin\current') Write-Output ('keepAgent=' + $keepAgent) Write-Output ('keepAdmin=' + $keepAdmin) function Try-Remove([string]$path) { try { Remove-Item $path -Recurse -Force -ErrorAction Stop Write-Output ('REMOVED ' + $path) return $true } catch { Write-Output ('LOCK ' + $path + ' :: ' + $_.Exception.Message) return $false } } # Stop python/java only if commandline clearly points at OLD release paths we will delete $keepAgentRoot = $null if ($keepAgent) { # .../releases//agent -> releases/ $keepAgentRoot = Split-Path $keepAgent -Parent } Get-CimInstance Win32_Process | ForEach-Object { $cl = $_.CommandLine if (-not $cl) { return } if ($cl -like '*\agent\releases\*' -and $keepAgentRoot -and $cl -notlike ('*' + $keepAgentRoot + '*')) { if ($cl -like '*python*' -or $cl -like '*http_app*' -or $cl -like '*worker_app*') { Write-Output ('stop stale pid=' + $_.ProcessId) Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } } } Start-Sleep -Seconds 2 if (Test-Path (Join-Path $Root 'agent\releases')) { Get-ChildItem (Join-Path $Root 'agent\releases') | Where-Object { $_.PSIsContainer } | ForEach-Object { $rel = $_.FullName $agentHomePath = Join-Path $rel 'agent' if ($keepAgent -and ($keepAgent -eq $agentHomePath -or $keepAgent.StartsWith($rel + '\'))) { Write-Output ('KEEP ' + $rel) } else { Try-Remove $rel | Out-Null } } } if (Test-Path (Join-Path $Root 'admin\releases')) { Get-ChildItem (Join-Path $Root 'admin\releases') | Where-Object { $_.PSIsContainer } | ForEach-Object { $rel = $_.FullName $dist = Join-Path $rel 'dist' if ($keepAdmin -and ($keepAdmin -eq $dist -or $keepAdmin.StartsWith($rel + '\'))) { Write-Output ('KEEP ' + $rel) } else { Try-Remove $rel | Out-Null } } } # trim env bak keep 2 newest Get-ChildItem $Root -Filter '.env.bak*' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -Skip 2 | ForEach-Object { Try-Remove $_.FullName | Out-Null } Write-Output 'CLEANUP_AFTER_OK'