#requires -Version 5.1 <# Install/update the visible RemoteWipeAgent Windows service. Run as Administrator. Get a single-use enrollment code from the dashboard first; codes expire in 15 minutes. .\install.ps1 -BaseUrl https://remotewipe.ccmecomglobal.com -EnrollmentToken '' RW_ENROLLMENT_TOKEN is also accepted for deployment tools. No prompts or cleanup commands are run by this installer. A new code is needed after an unsuccessful enrollment attempt. #> [CmdletBinding()] param( [string]$BaseUrl = 'https://remotewipe.ccmecomglobal.com', [string]$EnrollmentToken = $env:RW_ENROLLMENT_TOKEN ) function Assert-RwWindowsAdministrator { if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT -or -not [Environment]::Is64BitOperatingSystem -or $env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64') { throw 'RemoteWipe requires Windows x64.' } if (-not [Environment]::Is64BitProcess) { throw 'Run the 64-bit Windows PowerShell as Administrator (not PowerShell x86).' } $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) { throw 'Open Windows PowerShell using Run as Administrator and run the dashboard command again.' } } function Get-RwBaseUrl([string]$Value) { $uri = $null if (-not [Uri]::TryCreate($Value, [UriKind]::Absolute, [ref]$uri) -or $uri.UserInfo -or $uri.Query -or $uri.Fragment -or ($uri.Scheme -ne 'https' -and -not ($uri.Scheme -eq 'http' -and $uri.IsLoopback))) { throw 'BaseUrl must be HTTPS without credentials, query, or fragment. HTTP is allowed only on localhost.' } return $uri.AbsoluteUri.TrimEnd('/') } function Assert-RwNoReparsePoint([string]$Path, [switch]$Recursive) { $fullPath = [IO.Path]::GetFullPath($Path) $cursor = $fullPath while ($cursor) { if (Test-Path -LiteralPath $cursor) { $item = Get-Item -LiteralPath $cursor -Force if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'An installation/state path contains a symbolic link or junction. Remove it before installing.' } } $parent = [IO.Directory]::GetParent($cursor) if ($null -eq $parent) { break } $cursor = $parent.FullName } if ($Recursive -and (Test-Path -LiteralPath $fullPath)) { # Check each directory before descending, so junctions are never followed. $pending = New-Object 'System.Collections.Generic.Stack[string]' $pending.Push($fullPath) while ($pending.Count -gt 0) { foreach ($item in Get-ChildItem -LiteralPath $pending.Pop() -Force) { if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'An installation/state directory contains a symbolic link or junction.' } if ($item.PSIsContainer) { $pending.Push($item.FullName) } } } } } function Set-RwPrivateDirectory([string]$Path) { Assert-RwNoReparsePoint $Path -Recursive if (-not (Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null } if (-not (Get-Item -LiteralPath $Path).PSIsContainer) { throw 'An installation path is not a directory.' } # SID-based ACLs work on every Windows display language. Remove inherited/explicit grants. $system = New-Object Security.Principal.SecurityIdentifier('S-1-5-18') $admins = New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544') $paths = @((Get-Item -LiteralPath $Path)) + @(Get-ChildItem -LiteralPath $Path -Recurse -Force) foreach ($item in $paths) { if ($item.PSIsContainer) { $acl = New-Object Security.AccessControl.DirectorySecurity $inheritance = [Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' } else { $acl = New-Object Security.AccessControl.FileSecurity $inheritance = [Security.AccessControl.InheritanceFlags]::None } $acl.SetAccessRuleProtection($true, $false) $acl.SetOwner($admins) foreach ($sid in @($system, $admins)) { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', $inheritance, 'None', 'Allow') $acl.AddAccessRule($rule) } Set-Acl -LiteralPath $item.FullName -AclObject $acl } } function Invoke-RwEnrollment([string]$Url, [string]$Token) { try { $response = Invoke-WebRequest -Uri "$Url/api/enrollment/redeem" -Method Post ` -Headers @{ Authorization = "Bearer $Token" } -ContentType 'application/json' -Body '{}' ` -MaximumRedirection 0 -UseBasicParsing -TimeoutSec 60 $enrollment = $response.Content | ConvertFrom-Json } catch { throw 'Enrollment failed. Create a new installation code in the dashboard and verify network access; codes are single-use and expire after 15 minutes.' } if ([string]::IsNullOrWhiteSpace([string]$enrollment.AgentToken) -or [string]$enrollment.AgentToken -match '\s' -or [string]$enrollment.PackageSha256 -notmatch '^[a-fA-F0-9]{64}$') { throw 'The relay returned an invalid enrollment response. No service files were changed.' } $relayUri = $null if (-not [Uri]::TryCreate([string]$enrollment.RelayUrl, [UriKind]::Absolute, [ref]$relayUri) -or $relayUri.UserInfo -or $relayUri.Fragment -or $relayUri.Query -or ($relayUri.Scheme -ne 'wss' -and -not ($relayUri.Scheme -eq 'ws' -and $relayUri.IsLoopback))) { throw 'The relay returned an invalid secure WebSocket address.' } return $enrollment } function Save-RwPackage([string]$Url, [string]$Token, [string]$Path) { try { Invoke-WebRequest -Uri "$Url/api/agent-package" -Headers @{ Authorization = "Bearer $Token" } ` -OutFile $Path -MaximumRedirection 0 -UseBasicParsing -TimeoutSec 300 | Out-Null } catch { throw 'Agent download failed. The current installation is unchanged. Create a new dashboard installation code to retry.' } } function Expand-RwVerifiedPackage([string]$ZipPath, [string]$Destination, [string]$Sha256) { if ($Sha256 -notmatch '^[a-fA-F0-9]{64}$' -or (Get-FileHash -LiteralPath $ZipPath -Algorithm SHA256).Hash -ne $Sha256) { throw 'Agent package SHA-256 does not match the authenticated enrollment response.' } Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [IO.Compression.ZipFile]::OpenRead($ZipPath) try { $root = [IO.Path]::GetFullPath($Destination).TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) $totalBytes = [long]0 if ($zip.Entries.Count -eq 0 -or $zip.Entries.Count -gt 4096) { throw 'Agent package has an invalid file count.' } foreach ($entry in $zip.Entries) { $name = $entry.FullName.Replace('\', '/') $segments = $name.TrimEnd('/').Split('/') $attributes = [long]$entry.ExternalAttributes -band 0xffffffffL $unixType = ($attributes -shr 16) -band 0xf000 if ($name.StartsWith('/') -or $name.Contains(':') -or $name.Contains([char]0) -or ($attributes -band 0x400) -ne 0 -or ($unixType -ne 0 -and $unixType -ne 0x8000 -and $unixType -ne 0x4000)) { throw 'Agent package contains an unsafe path or link.' } foreach ($segment in $segments) { if (-not $segment -or $segment -eq '.' -or $segment -eq '..' -or $segment -match '[. ]$|[<>"|?*\x00-\x1f]' -or $segment -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)') { throw 'Agent package contains an unsafe Windows filename.' } } $target = [IO.Path]::GetFullPath((Join-Path $Destination ($name.Replace('/', [IO.Path]::DirectorySeparatorChar)))) if (-not $target.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -or -not $seen.Add($target.TrimEnd([IO.Path]::DirectorySeparatorChar))) { throw 'Agent package contains a duplicate or escaping path.' } $totalBytes += $entry.Length if ($totalBytes -gt 2GB) { throw 'Agent package exceeds the 2 GB extraction limit.' } } if (-not $seen.Contains((Join-Path $Destination 'RemoteWipe.Agent.exe'))) { throw 'Agent package is missing RemoteWipe.Agent.exe at its root.' } # Validate every archive entry before extracting any of them. Never overwrite existing files. foreach ($entry in $zip.Entries) { $name = $entry.FullName.Replace('\', '/').Replace('/', [IO.Path]::DirectorySeparatorChar) $target = Join-Path $Destination $name if ($entry.FullName.EndsWith('/') -or $entry.FullName.EndsWith('\')) { [IO.Directory]::CreateDirectory($target) | Out-Null } else { [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target)) | Out-Null [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $false) } } $exe = Get-Item -LiteralPath (Join-Path $Destination 'RemoteWipe.Agent.exe') if ($exe.PSIsContainer -or $exe.Length -eq 0) { throw 'Agent executable is missing or empty.' } Assert-RwNoReparsePoint $Destination -Recursive } finally { $zip.Dispose() } } function Initialize-RwRecoveryApi { if ('RemoteWipeInstaller.RecoverySnapshot' -as [type]) { return } # Preserve native service recovery settings, including the SCM's in-memory copy. Add-Type -TypeDefinition @' using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace RemoteWipeInstaller { public sealed class RecoverySnapshot : IDisposable { [StructLayout(LayoutKind.Sequential)] struct FailureActions { public uint Reset; public IntPtr Reboot, Command; public uint Count; public IntPtr Actions; } [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr OpenSCManager(string machine, string database, uint access); [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr OpenService(IntPtr manager, string name, uint access); [DllImport("advapi32.dll", SetLastError=true)] static extern bool CloseServiceHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool QueryServiceConfig2(IntPtr service, uint level, IntPtr buffer, uint size, out uint needed); [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool ChangeServiceConfig2(IntPtr service, uint level, IntPtr buffer); IntPtr actions, flag, emptyActions; static IntPtr Open(uint access) { IntPtr manager = OpenSCManager(null, null, 1); if (manager == IntPtr.Zero) throw new Win32Exception(); try { IntPtr service = OpenService(manager, "RemoteWipeAgent", access); if (service == IntPtr.Zero) throw new Win32Exception(); return service; } finally { CloseServiceHandle(manager); } } static IntPtr Read(IntPtr service, uint level) { uint needed; QueryServiceConfig2(service, level, IntPtr.Zero, 0, out needed); if (needed == 0 || needed > 8192) throw new Win32Exception(); IntPtr buffer = Marshal.AllocHGlobal((int)needed); if (!QueryServiceConfig2(service, level, buffer, needed, out needed)) { int error = Marshal.GetLastWin32Error(); Marshal.FreeHGlobal(buffer); throw new Win32Exception(error); } return buffer; } public static RecoverySnapshot Capture() { IntPtr service = Open(1); RecoverySnapshot snapshot = new RecoverySnapshot(); try { snapshot.actions = Read(service, 2); snapshot.flag = Read(service, 4); FailureActions settings = (FailureActions)Marshal.PtrToStructure(snapshot.actions, typeof(FailureActions)); if (settings.Count == 0) { // A non-null array with zero actions clears the newly installed recovery policy. snapshot.emptyActions = Marshal.AllocHGlobal(8); settings.Actions = snapshot.emptyActions; Marshal.StructureToPtr(settings, snapshot.actions, false); } return snapshot; } catch { snapshot.Dispose(); throw; } finally { CloseServiceHandle(service); } } public void Restore() { IntPtr service = Open(0x12); // SERVICE_CHANGE_CONFIG | SERVICE_START try { if (!ChangeServiceConfig2(service, 2, actions)) throw new Win32Exception(); if (!ChangeServiceConfig2(service, 4, flag)) throw new Win32Exception(); } finally { CloseServiceHandle(service); } } public void Dispose() { foreach (IntPtr buffer in new IntPtr[] { actions, flag, emptyActions }) { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } actions = flag = emptyActions = IntPtr.Zero; } } } '@ } function Get-RwServiceSnapshot { $service = Get-CimInstance Win32_Service -Filter "Name='RemoteWipeAgent'" if ($null -eq $service) { return $null } if ($service.StartName -ne 'LocalSystem' -and $service.StartName -ne 'NT AUTHORITY\SYSTEM') { throw 'The existing RemoteWipeAgent uses a custom service account. Migrate it to LocalSystem before using this installer.' } $values = @{} $key = Get-Item -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\RemoteWipeAgent' foreach ($name in @('ImagePath', 'Start', 'DelayedAutoStart', 'FailureActions', 'FailureActionsOnNonCrashFailures', 'Description')) { if ($key.GetValueNames() -contains $name) { $values[$name] = @{ Value = $key.GetValue($name, $null, 'DoNotExpandEnvironmentNames'); Kind = $key.GetValueKind($name) } } } return [pscustomobject]@{ PathName = $service.PathName; WasRunning = ($service.State -ne 'Stopped'); Registry = $values Recovery = $null } } function Save-RwRecoverySnapshot($Snapshot) { if ($null -ne $Snapshot) { Initialize-RwRecoveryApi $Snapshot.Recovery = [RemoteWipeInstaller.RecoverySnapshot]::Capture() } } function Get-RwInstallDirectory($Snapshot) { $programFiles = [Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles) $defaultDirectory = Join-Path $programFiles 'RemoteWipeAgent' $legacyDirectory = 'C:\RemoteWipeAgent' if ($null -ne $Snapshot) { $binary = [Environment]::ExpandEnvironmentVariables([string]$Snapshot.PathName) if ($binary -match '^\s*"([^"\r\n]+\.exe)"\s*$') { $binary = $matches[1] } elseif ($binary -notmatch '^[^"\r\n]+\.exe$') { throw 'The existing service command contains unsupported arguments; update it manually.' } if ([IO.Path]::GetFileName($binary) -ne 'RemoteWipe.Agent.exe') { throw 'The existing service executable name is unexpected.' } $directory = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($binary)) } elseif (Test-Path -LiteralPath $legacyDirectory) { $directory = $legacyDirectory } else { $directory = $defaultDirectory } Assert-RwManagedInstallDirectory $directory $defaultDirectory $legacyDirectory return $directory } function Assert-RwManagedInstallDirectory([string]$Directory, [string]$DefaultDirectory, [string]$LegacyDirectory) { $canonical = [IO.Path]::GetFullPath($Directory).TrimEnd([IO.Path]::DirectorySeparatorChar) $allowed = @( [IO.Path]::GetFullPath($DefaultDirectory).TrimEnd([IO.Path]::DirectorySeparatorChar), [IO.Path]::GetFullPath($LegacyDirectory).TrimEnd([IO.Path]::DirectorySeparatorChar) ) # Updates replace the whole directory: never infer ownership from an executable filename. if ($Directory.StartsWith('\\') -or ($allowed -notcontains $canonical)) { throw 'Automatic installation supports only the dedicated Program Files\RemoteWipeAgent or C:\RemoteWipeAgent directory. Migrate this custom service path manually.' } } function Get-RwStateDirectory { return Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)) 'RemoteWipeAgent' } function Write-RwAgentConfiguration([string]$Stage, [string]$Previous, $Enrollment) { $machineTag = '' $configPath = Join-Path $Previous 'appsettings.json' if (Test-Path -LiteralPath $configPath) { try { $oldConfig = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json } catch { throw 'Existing appsettings.json is invalid. Repair it before updating; its contents were not printed.' } if ($null -ne $oldConfig.AgentSettings.MachineTag) { $machineTag = [string]$oldConfig.AgentSettings.MachineTag } } # Do not retain stale credential overrides from a package or an earlier installation. Get-ChildItem -LiteralPath $Stage -Filter 'appsettings*.json' -File | Remove-Item -Force $config = @{ Logging = @{ LogLevel = @{ Default = 'Information'; 'Microsoft.Hosting.Lifetime' = 'Information' } } AgentSettings = @{ AgentToken = [string]$Enrollment.AgentToken; RelayUrl = [string]$Enrollment.RelayUrl; MachineTag = $machineTag } } $utf8 = New-Object Text.UTF8Encoding($false) [IO.File]::WriteAllText((Join-Path $Stage 'appsettings.json'), ($config | ConvertTo-Json -Depth 6), $utf8) } function Invoke-RwSc([string[]]$Arguments) { & "$env:SystemRoot\System32\sc.exe" @Arguments | Out-Null if ($LASTEXITCODE -ne 0) { throw 'Windows Service Control Manager rejected a service configuration change.' } } function Stop-RwService { $service = Get-Service -Name 'RemoteWipeAgent' -ErrorAction SilentlyContinue if ($null -ne $service -and $service.Status -ne 'Stopped') { Stop-Service -Name 'RemoteWipeAgent' -ErrorAction Stop $service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, [TimeSpan]::FromSeconds(30)) } } function Start-RwService { Start-Service -Name 'RemoteWipeAgent' -ErrorAction Stop $service = Get-Service -Name 'RemoteWipeAgent' $service.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running, [TimeSpan]::FromSeconds(30)) Start-Sleep -Seconds 3 $service.Refresh() if ($service.Status -ne 'Running') { throw 'The agent service stopped immediately after startup.' } } function Set-RwService([string]$Directory, [bool]$Existing) { $binary = '"' + (Join-Path $Directory 'RemoteWipe.Agent.exe') + '"' if ($Existing) { Set-RwServicePath $binary 'Automatic' } else { New-Service -Name 'RemoteWipeAgent' -BinaryPathName $binary -DisplayName 'RemoteWipe Agent' ` -Description 'Company-managed RemoteWipe agent. Visible device management service.' -StartupType Automatic | Out-Null } Invoke-RwSc -Arguments @('failure', 'RemoteWipeAgent', 'reset=', '86400', 'actions=', 'restart/60000/restart/60000/restart/60000') Invoke-RwSc -Arguments @('failureflag', 'RemoteWipeAgent', '1') } function Set-RwServicePath([string]$Binary, [string]$StartMode) { # CIM retains the executable's quotation marks on Windows PowerShell 5.1. $service = Get-CimInstance Win32_Service -Filter "Name='RemoteWipeAgent'" $result = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{ PathName = $Binary; StartMode = $StartMode } if ($result.ReturnValue -ne 0) { throw 'Windows rejected the agent service path/startup configuration.' } } function Restore-RwService($Snapshot) { if ($null -eq $Snapshot) { if (Get-Service -Name 'RemoteWipeAgent' -ErrorAction SilentlyContinue) { Invoke-RwSc -Arguments @('delete', 'RemoteWipeAgent') } return } $start = switch ([int]$Snapshot.Registry['Start'].Value) { 2 { 'Automatic' }; 3 { 'Manual' }; 4 { 'Disabled' }; default { 'Manual' } } Set-RwServicePath ([string]$Snapshot.PathName) $start $Snapshot.Recovery.Restore() $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Services\RemoteWipeAgent', $true) try { foreach ($name in @('ImagePath', 'Start', 'DelayedAutoStart', 'FailureActions', 'FailureActionsOnNonCrashFailures', 'Description')) { if ($Snapshot.Registry.ContainsKey($name)) { $saved = $Snapshot.Registry[$name] $key.SetValue($name, $saved.Value, $saved.Kind) } else { $key.DeleteValue($name, $false) } } } finally { $key.Dispose() } if ($Snapshot.WasRunning) { Start-RwService } } function Invoke-RwAgentInstallation([string]$Url, [string]$Token) { $ErrorActionPreference = 'Stop' Assert-RwWindowsAdministrator $url = Get-RwBaseUrl $Url if ([string]::IsNullOrWhiteSpace($Token) -or $Token -match '\s') { throw 'Create an installation code in the dashboard, then pass -EnrollmentToken or set RW_ENROLLMENT_TOKEN. No interactive input is required.' } [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $snapshot = Get-RwServiceSnapshot $installDir = Get-RwInstallDirectory $snapshot $stateDir = Get-RwStateDirectory Assert-RwNoReparsePoint $installDir -Recursive Assert-RwNoReparsePoint $stateDir -Recursive $operation = [Guid]::NewGuid().ToString('N') $stage = $installDir + '.stage-' + $operation $backup = $installDir + '.backup-' + $operation $workDir = $installDir + '.work-' + $operation $zipPath = Join-Path $workDir 'agent.zip' $changed = $false $hadPreviousFiles = Test-Path -LiteralPath $installDir $backupMoved = $false $newFilesMoved = $false $keepBackup = $false try { Set-RwPrivateDirectory $workDir Set-RwPrivateDirectory $stage Write-Host 'Downloading and validating the company agent package...' $enrollment = Invoke-RwEnrollment $url $Token $Token = $null Save-RwPackage $url ([string]$enrollment.AgentToken) $zipPath Expand-RwVerifiedPackage $zipPath $stage ([string]$enrollment.PackageSha256) Write-RwAgentConfiguration $stage $installDir $enrollment Set-RwPrivateDirectory $stage # Preserve the agent identity and all state files; only permissions are tightened. Set-RwPrivateDirectory $stateDir if ($hadPreviousFiles) { Set-RwPrivateDirectory $installDir } Save-RwRecoverySnapshot $snapshot Write-Host 'Installing the visible RemoteWipeAgent Windows service...' $changed = $true Stop-RwService if ($hadPreviousFiles) { Move-Item -LiteralPath $installDir -Destination $backup $backupMoved = $true } Move-Item -LiteralPath $stage -Destination $installDir $newFilesMoved = $true Set-RwService $installDir ($null -ne $snapshot) Start-RwService Write-Host 'Installed successfully. RemoteWipeAgent is running; verify this device is Online in the dashboard. No user data was deleted.' } catch { $failure = $_.Exception.Message if ($changed) { try { Stop-RwService if ($newFilesMoved -and (Test-Path -LiteralPath $installDir)) { Assert-RwNoReparsePoint $installDir -Recursive Remove-Item -LiteralPath $installDir -Recurse -Force } if ($backupMoved) { Move-Item -LiteralPath $backup -Destination $installDir; $backupMoved = $false } Restore-RwService $snapshot $failure += ' Previous files and service settings were restored.' } catch { $keepBackup = $true $failure += ' Automatic rollback could not finish. Repair the RemoteWipeAgent service as Administrator.' if (Test-Path -LiteralPath $backup) { $failure += " Keep the protected previous-version backup at '$backup'." } elseif (Test-Path -LiteralPath $installDir) { $failure += " Installation files remain at '$installDir'." } } } throw $failure } finally { $enrollment = $null $Token = $null foreach ($path in @($workDir, $stage)) { if (Test-Path -LiteralPath $path) { try { Assert-RwNoReparsePoint $path -Recursive; Remove-Item -LiteralPath $path -Recurse -Force } catch { Write-Warning 'A protected temporary installation directory could not be removed.' } } } if ($backupMoved -and -not $keepBackup -and (Test-Path -LiteralPath $backup)) { try { Assert-RwNoReparsePoint $backup -Recursive; Remove-Item -LiteralPath $backup -Recurse -Force } catch { Write-Warning 'Installation succeeded, but the protected previous-version backup could not be removed.' } } if ($null -ne $snapshot -and $null -ne $snapshot.Recovery) { $snapshot.Recovery.Dispose() } } } function Install-RwAgent([string]$Url, [string]$Token) { Assert-RwWindowsAdministrator $mutex = New-Object Threading.Mutex($false, 'Global\RemoteWipeAgentInstaller') $ownsMutex = $false try { try { $ownsMutex = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $ownsMutex = $true } if (-not $ownsMutex) { throw 'Another RemoteWipe installation is running. Wait for it to finish before retrying.' } Invoke-RwAgentInstallation -Url $Url -Token $Token } finally { if ($ownsMutex) { $mutex.ReleaseMutex() } $mutex.Dispose() } } # Dot-sourcing loads functions only, for review and non-destructive automated tests. if ($MyInvocation.InvocationName -ne '.') { Install-RwAgent -Url $BaseUrl -Token $EnrollmentToken }