#requires -Version 5.1 <# Infostruction Windows Datto RMM migration helper, revision 2026-11-03. Community configuration-file method, not a vendor-supported migration guarantee. Preview by default. Use -Apply only after a pilot and with independent endpoint access. Success means local configuration and service checks passed. Verify the destination console, policy, monitoring and remote access separately before retiring source access. The macOS archive and Linux agent are NOT covered by this revision. #> [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')] param( [string]$DestinationAccount, [string]$DestinationHost, [guid]$DestinationSite, [ValidateRange(5,180)][int]$TimeoutSeconds=60, [switch]$Apply ) function Assert-MigrationDestination { param([string]$Account,[string]$HostName,[guid]$SiteId) if ($Account -notmatch '^[a-z][a-z0-9]{5,63}$' -or $Account -match '^vid0+$' -or $HostName -notmatch '^[a-z0-9-]+\.centrastage\.net$' -or $SiteId -eq [guid]::Empty) { throw 'Supply a real destination AccountUid, control-channel hostname and nonzero site GUID. Copy them from the destination tenant.' } } function Wait-MigrationCondition { param([scriptblock]$Test,[ValidateRange(1,180)][int]$TimeoutSeconds,[string]$Description) $timer=[Diagnostics.Stopwatch]::StartNew() do { if (& $Test) { return } if ($timer.Elapsed.TotalSeconds -ge $TimeoutSeconds) { throw "Timed out: $Description" } Start-Sleep -Milliseconds 200 } while ($true) } function Get-MigrationUdfRows { param([object[]]$Variables) foreach ($variable in $Variables) { $match=[regex]::Match($variable.Name,'^UDF_(\d+)$') if ($match.Success -and [int]$match.Groups[1].Value -ge 1 -and [int]$match.Groups[1].Value -le 30 -and -not [string]::IsNullOrWhiteSpace($variable.Value)) { [pscustomobject]@{UDFnumber=('Custom' + [int]$match.Groups[1].Value);UDFData=[string]$variable.Value} } } } function Restore-MigrationConfiguration { param([string]$BackupPath,[string]$ConfigPath) Copy-Item -LiteralPath $BackupPath -Destination $ConfigPath -Force -ErrorAction Stop } function Set-MigrationServiceState { param([ValidateSet('Stopped','Running')][string]$DesiredState,[ValidateRange(1,180)][int]$TimeoutSeconds) $timer=[Diagnostics.Stopwatch]::StartNew() if ((Get-Service CagService -ErrorAction Stop).Status -eq $DesiredState) { return } if ($DesiredState -eq 'Stopped') { $verb='stop'; $alreadyThere=1062 } else { $verb='start'; $alreadyThere=1056 } # Stop-Service/Start-Service can block before a caller's status-poll timeout begins. $request=Start-Process -FilePath "$env:SystemRoot\System32\sc.exe" -ArgumentList @($verb,'CagService') -WindowStyle Hidden -PassThru -ErrorAction Stop $budget=[int][Math]::Max(1,($TimeoutSeconds*1000-$timer.Elapsed.TotalMilliseconds)) if (-not $request.WaitForExit($budget)) { try { $request.Kill() } catch { } throw "SCM $verb request exceeded its $TimeoutSeconds second budget. No subsequent file restoration is permitted." } if ($request.ExitCode -notin @(0,$alreadyThere)) { throw "SCM $verb request failed with exit code $($request.ExitCode)." } while ((Get-Service CagService -ErrorAction Stop).Status -ne $DesiredState) { if ($timer.Elapsed.TotalSeconds -ge $TimeoutSeconds) { throw "CagService did not reach $DesiredState within $TimeoutSeconds seconds." } Start-Sleep -Milliseconds 200 } } function Get-MigrationRecoveryScript { param([string]$BackupPath,[string]$ConfigPath,[object[]]$Manifest,[string]$TaskName,[int]$TimeoutSeconds) $backupQuoted=$BackupPath.Replace("'","''"); $cfgQuoted=$ConfigPath.Replace("'","''") $taskQuoted=$TaskName.Replace("'","''") $lines=@( '$ErrorActionPreference=''Stop''', ('function Set-MigrationServiceState {' + (Get-Command Set-MigrationServiceState).Definition + "`n}"), "Set-MigrationServiceState -DesiredState Stopped -TimeoutSeconds $TimeoutSeconds", "Copy-Item -LiteralPath '$backupQuoted' -Destination '$cfgQuoted' -Force -ErrorAction Stop" ) foreach ($item in $Manifest) { $target=$item.Path.Replace("'","''"); $source=$item.Backup.Replace("'","''") if ($item.Existed) { $lines += "Copy-Item -LiteralPath '$source' -Destination '$target' -Force -ErrorAction Stop" } else { $lines += "if (Test-Path -LiteralPath '$target' -PathType Leaf) { Remove-Item -LiteralPath '$target' -Force -ErrorAction Stop }" } } $lines += "Set-MigrationServiceState -DesiredState Running -TimeoutSeconds $TimeoutSeconds" $lines += "Unregister-ScheduledTask -TaskName '$taskQuoted' -Confirm:`$false -ErrorAction Stop" $lines -join ";`n" } function Assert-MigrationArtifactPath { param([string]$ArtifactPath,[string[]]$AllowedRoots) $full=[IO.Path]::GetFullPath($ArtifactPath) $within=$false foreach ($allowed in $AllowedRoots) { if ($full.StartsWith(([IO.Path]::GetFullPath($allowed).TrimEnd('\') + '\'),[StringComparison]::OrdinalIgnoreCase)) { $within=$true } } if (-not $within) { throw "Agent artifact is outside the expected CentraStage directories: $full" } $parent=Split-Path -Parent $full while ($parent) { if (Test-Path -LiteralPath $parent) { if ((Get-Item -LiteralPath $parent -Force -ErrorAction Stop).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Reparse point in agent artifact path: $parent" } } $next=Split-Path -Parent $parent if ($next -eq $parent) { break } $parent=$next } $full } function Invoke-DattoMigration { [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')] param([string]$DestinationAccount,[string]$DestinationHost,[guid]$DestinationSite,[int]$TimeoutSeconds=60,[switch]$Apply) $ErrorActionPreference='Stop' Assert-MigrationDestination -Account $DestinationAccount -HostName $DestinationHost -SiteId $DestinationSite if ($env:OS -ne 'Windows_NT' -or ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess)) { throw 'Use native 64-bit Windows PowerShell on a 64-bit endpoint.' } $identity=[Security.Principal.WindowsIdentity]::GetCurrent() if (-not ([Security.Principal.WindowsPrincipal]$identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run as administrator or SYSTEM.' } if ([Environment]::Is64BitOperatingSystem) { $programRoot=${env:ProgramFiles(x86)} } else { $programRoot=$env:ProgramFiles } $install=Join-Path $programRoot 'CentraStage' $cfg=Join-Path $install 'CagService.exe.config' $reg='HKLM:\SOFTWARE\CentraStage' [xml]$configuration=Get-Content -LiteralPath $cfg -Raw -ErrorAction Stop $xpath="/configuration/applicationSettings/CentraStage.Cag.Core.AppSettings/setting[@name='{0}']/value" foreach ($setting in 'CsIp','Profile','AccountUid') { if (-not $configuration.SelectSingleNode(($xpath -f $setting))) { throw "Expected configuration setting missing: $setting" } } $service=Get-Service CagService -ErrorAction Stop if ($service.Status -ne 'Running') { throw 'Source CagService must be running before this migration. Repair source connectivity first.' } $programDataRoot=Join-Path $env:ProgramData 'CentraStage' $agent=(Get-ItemProperty -LiteralPath $reg -Name AgentFolderLocation -ErrorAction Stop).AgentFolderLocation if ([string]::IsNullOrWhiteSpace($agent)) { throw 'AgentFolderLocation is empty.' } $roots=@($install,$programDataRoot,(Join-Path $env:ProgramFiles 'CentraStage')) $artifacts=@( (Join-Path $programDataRoot 'AuditSnapshot.xml'), (Join-Path $agent 'AEMAgent\Settings.json'), (Join-Path $agent 'deviceuid') ) | ForEach-Object { Assert-MigrationArtifactPath -ArtifactPath $_ -AllowedRoots $roots } $udfs=@(Get-MigrationUdfRows -Variables @(Get-ChildItem Env:)) $preview=[pscustomobject]@{ConfigPath=$cfg;DestinationAccount=$DestinationAccount;DestinationHost=$DestinationHost;DestinationSite=$DestinationSite;IdentityFiles=$artifacts;UdfValuesCaptured=$udfs.Count;Status='Preview only'} if (-not $Apply) { return $preview } if (-not $PSCmdlet.ShouldProcess($env:COMPUTERNAME,'Back up local state, replace Datto RMM destination and restart agent')) { return $preview } # Program Files supplies a protected location for config and identity backups. $backupDirectory=Join-Path $install ('MigrationBackup-' + [guid]::NewGuid().ToString('N')) [void](New-Item -ItemType Directory -Path $backupDirectory -ErrorAction Stop) $backup=Join-Path $backupDirectory 'CagService.exe.config' Copy-Item -LiteralPath $cfg -Destination $backup -ErrorAction Stop $manifest=@(); $index=0 foreach ($artifact in $artifacts) { $index++; $exists=Test-Path -LiteralPath $artifact -PathType Leaf $copy=Join-Path $backupDirectory "identity-$index.backup" if ($exists) { Copy-Item -LiteralPath $artifact -Destination $copy -ErrorAction Stop } $manifest += [pscustomobject]@{Path=$artifact;Existed=$exists;Backup=$copy} } $manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $backupDirectory 'identity-manifest.json') -Encoding UTF8 $udfs | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $backupDirectory 'udfs.json') -Encoding UTF8 # Recovery handles an interrupted LOCAL cutover. It cannot validate cloud enrollment. $taskName='Infostruction-RMM-Recovery-' + [guid]::NewGuid().ToString('N') $recovery=Get-MigrationRecoveryScript -BackupPath $backup -ConfigPath $cfg -Manifest $manifest -TaskName $taskName -TimeoutSeconds $TimeoutSeconds $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($recovery)) $action=New-ScheduledTaskAction -Execute "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-NoProfile -NonInteractive -EncodedCommand $encoded" Register-ScheduledTask -TaskName $taskName -Action $action -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(20)) ` -Principal (New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest) ` -Settings (New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -RestartCount 2 -RestartInterval (New-TimeSpan -Minutes 1)) -ErrorAction Stop | Out-Null try { Set-MigrationServiceState -DesiredState Stopped -TimeoutSeconds $TimeoutSeconds Stop-Process -Name AEMAgent -Force -ErrorAction SilentlyContinue $configuration.SelectSingleNode(($xpath -f 'CsIp')).InnerText=$DestinationHost $configuration.SelectSingleNode(($xpath -f 'Profile')).InnerText=$DestinationSite.ToString('D') $configuration.SelectSingleNode(($xpath -f 'AccountUid')).InnerText=$DestinationAccount $configuration.Save($cfg) foreach ($artifact in $artifacts) { if (Test-Path -LiteralPath $artifact -PathType Leaf) { Remove-Item -LiteralPath $artifact -Force -ErrorAction Stop } } Set-MigrationServiceState -DesiredState Running -TimeoutSeconds $TimeoutSeconds [xml]$readback=Get-Content -LiteralPath $cfg -Raw if ($readback.SelectSingleNode(($xpath -f 'AccountUid')).InnerText -ne $DestinationAccount -or $readback.SelectSingleNode(($xpath -f 'Profile')).InnerText -ine $DestinationSite.ToString('D') -or $readback.SelectSingleNode(($xpath -f 'CsIp')).InnerText -ine $DestinationHost) { throw 'Local destination read-back mismatch.' } foreach ($udf in $udfs) { New-ItemProperty -LiteralPath $reg -Name $udf.UDFnumber -Value $udf.UDFData -PropertyType String -Force -ErrorAction Stop | Out-Null } Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop } catch { $failure=$_.Exception.Message try { Set-MigrationServiceState -DesiredState Stopped -TimeoutSeconds $TimeoutSeconds Restore-MigrationConfiguration -BackupPath $backup -ConfigPath $cfg foreach ($item in $manifest) { if ($item.Existed) { Copy-Item -LiteralPath $item.Backup -Destination $item.Path -Force -ErrorAction Stop } elseif (Test-Path -LiteralPath $item.Path -PathType Leaf) { Remove-Item -LiteralPath $item.Path -Force -ErrorAction Stop } } Set-MigrationServiceState -DesiredState Running -TimeoutSeconds $TimeoutSeconds Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop } catch { throw "Local cutover failed ($failure); recovery also failed ($($_.Exception.Message)). Recovery task $taskName remains scheduled. Use independent access and backups at $backupDirectory." } throw "Local cutover failed and local files were restored: $failure. Confirm source console connectivity. Backups: $backupDirectory" } [pscustomobject]@{Status='Local cutover checks passed; destination console verification REQUIRED';BackupDirectory=$backupDirectory;RecoveryTask='Removed after local checks';UdfValuesRestored=$udfs.Count} } if ($MyInvocation.InvocationName -ne '.') { Invoke-DattoMigration @PSBoundParameters }