@echo off rem RustDesk-Wechselprogramm Version 2.4 - 2026-10-10 setlocal title RustDesk-Wechselprogramm v2.4 set "RUSTDESK_CMD_FILE=%~f0" powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$file=$env:RUSTDESK_CMD_FILE; $raw=[IO.File]::ReadAllText($file,[Text.Encoding]::UTF8); $marker='### POWERSHELL-PAYLOAD ###'; $pos=$raw.LastIndexOf($marker); if($pos -lt 0){throw 'PowerShell-Payload fehlt.'}; $code=$raw.Substring($pos+$marker.Length); Invoke-Expression $code" set "RUSTDESK_RESULT=%ERRORLEVEL%" endlocal & exit /b %RUSTDESK_RESULT% ### POWERSHELL-PAYLOAD ### $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $Version = '2.4' $ServerIp = '212.132.118.252' $PublicKey = 'pBgtFVLCMcNu0dTyi7QQjUHNj7gJ8gImP1wcpxveSLc=' $ServerInstallerName = "INSTALLATION_rustdesk-host=$ServerIp,key=$PublicKey,qs=0.exe" $InstallerUrl = "https://rustdesk.phocomp.de/$ServerInstallerName" $ConfiguredInstallerName = "rustdesk-host=$ServerIp,key=$PublicKey,.exe" $DownloadDirectory = Join-Path $env:TEMP "RustDesk-Neuinstallation-v$Version" $InstallerPath = Join-Path $DownloadDirectory $ConfiguredInstallerName $CmdFile = $env:RUSTDESK_CMD_FILE $ConfigString = "host=$ServerIp,key=$PublicKey," function Test-Administrator { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object Security.Principal.WindowsPrincipal($identity) return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } if (-not (Test-Administrator)) { $arguments = '/d /c ""{0}""' -f $CmdFile Start-Process -FilePath $env:ComSpec -Verb RunAs -ArgumentList $arguments exit 0 } $LogFile = Join-Path $env:PUBLIC "Desktop\RustDesk_Wechselprogramm_v$Version.log" $TranscriptStarted = $false try { Start-Transcript -Path $LogFile -Append | Out-Null $TranscriptStarted = $true } catch { Write-Warning "Protokoll konnte nicht gestartet werden: $($_.Exception.Message)" } function Write-Step { param([Parameter(Mandatory = $true)][string]$Text) Write-Host "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $Text" -ForegroundColor Cyan } function Get-UninstallEntries { $paths = @( 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' ) foreach ($path in $paths) { Get-ItemProperty -Path $path -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -and $_.DisplayName -match '^RustDesk(?:\s|$)' } } } function Get-RustDeskExe { param([array]$Entries) $candidates = New-Object System.Collections.Generic.List[string] foreach ($entry in $Entries) { if ($entry.InstallLocation) { $candidates.Add((Join-Path $entry.InstallLocation 'RustDesk.exe')) } if ($entry.DisplayIcon) { $icon = ([string]$entry.DisplayIcon).Trim('"') -replace ',\d+$', '' $candidates.Add($icon) } } if ($env:ProgramFiles) { $candidates.Add((Join-Path $env:ProgramFiles 'RustDesk\RustDesk.exe')) } if (${env:ProgramFiles(x86)}) { $candidates.Add((Join-Path ${env:ProgramFiles(x86)} 'RustDesk\RustDesk.exe')) } return $candidates | Where-Object { $_ -and (Test-Path -LiteralPath $_ -PathType Leaf) } | Select-Object -Unique -First 1 } function Get-InteractiveProfile { try { $loggedOnUser = (Get-CimInstance Win32_ComputerSystem).UserName if ([string]::IsNullOrWhiteSpace($loggedOnUser)) { return $env:USERPROFILE } $account = New-Object Security.Principal.NTAccount($loggedOnUser) $sid = $account.Translate([Security.Principal.SecurityIdentifier]).Value $key = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid" $path = (Get-ItemProperty -LiteralPath $key -Name ProfileImagePath).ProfileImagePath return [Environment]::ExpandEnvironmentVariables($path) } catch { return $env:USERPROFILE } } function Stop-RustDesk { Write-Step 'Beende RustDesk-Dienst und Prozesse.' Stop-Service -Name 'RustDesk' -Force -ErrorAction SilentlyContinue Get-Process -Name 'RustDesk' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 } function Remove-Folder { param([Parameter(Mandatory = $true)][string]$Path) if (Test-Path -LiteralPath $Path) { Write-Step "Loesche: $Path" Remove-Item -LiteralPath $Path -Recurse -Force } } function Download-Installer { Write-Step "Lade den vorkonfigurierten Client von $InstallerUrl" New-Item -Path $DownloadDirectory -ItemType Directory -Force | Out-Null Remove-Item -LiteralPath $InstallerPath -Force -ErrorAction SilentlyContinue [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-WebRequest -Uri $InstallerUrl -OutFile $InstallerPath -UseBasicParsing $file = Get-Item -LiteralPath $InstallerPath if ($file.Length -lt 5MB) { throw "Der Download ist mit $($file.Length) Bytes unerwartet klein. Die alte Installation wurde nicht veraendert." } $hash = (Get-FileHash -LiteralPath $InstallerPath -Algorithm SHA256).Hash Write-Host "Download erfolgreich. SHA256: $hash" -ForegroundColor DarkGray } function Invoke-RustDeskCli { param( [Parameter(Mandatory = $true)][string]$Exe, [Parameter(Mandatory = $true)][string[]]$Arguments, [int]$TimeoutSeconds = 20 ) $token = [Guid]::NewGuid().ToString('N') $stdout = Join-Path $env:TEMP "rustdesk-cli-$token.out" $stderr = Join-Path $env:TEMP "rustdesk-cli-$token.err" try { $process = Start-Process -FilePath $Exe ` -ArgumentList $Arguments ` -PassThru ` -WindowStyle Hidden ` -RedirectStandardOutput $stdout ` -RedirectStandardError $stderr if (-not $process.WaitForExit($TimeoutSeconds * 1000)) { Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue throw "RustDesk-Kommando hat nach $TimeoutSeconds Sekunden nicht geantwortet: $($Arguments -join ' ')" } $output = if (Test-Path -LiteralPath $stdout) { (Get-Content -LiteralPath $stdout -Raw -ErrorAction SilentlyContinue).Trim() } else { '' } $errorOutput = if (Test-Path -LiteralPath $stderr) { (Get-Content -LiteralPath $stderr -Raw -ErrorAction SilentlyContinue).Trim() } else { '' } if ($process.ExitCode -ne 0) { throw "RustDesk-Kommando fehlgeschlagen (Exitcode $($process.ExitCode)): $errorOutput" } return $output } finally { Remove-Item -LiteralPath $stdout, $stderr -Force -ErrorAction SilentlyContinue } } function Set-RustDeskServerConfiguration { param([Parameter(Mandatory = $true)][string]$Exe) Write-Step 'Importiere ID-Server und Key mit der offiziellen RustDesk-Konfigurationsfunktion.' Invoke-RustDeskCli -Exe $Exe -Arguments @('--config', $ConfigString) -TimeoutSeconds 30 | Out-Null Start-Sleep -Seconds 3 # Als zusaetzliche Absicherung werden genau dieselben Werte einzeln gesetzt. Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'custom-rendezvous-server', $ServerIp) | Out-Null Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'key', $PublicKey) | Out-Null # Relay- und API-Server werden absichtlich nicht gesetzt. Da vor der # Installation alle alten Konfigurationen entfernt werden, bleiben sie leer. Start-Sleep -Seconds 2 $actualServer = Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'custom-rendezvous-server') $actualKey = Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'key') $actualRelay = Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'relay-server') $actualApi = Invoke-RustDeskCli -Exe $Exe -Arguments @('--option', 'api-server') if ($actualServer -ne $ServerIp) { throw "Kontrolle fehlgeschlagen: ID-Server ist '$actualServer' statt '$ServerIp'." } if ($actualKey -ne $PublicKey) { throw 'Kontrolle fehlgeschlagen: Der Key wurde von RustDesk nicht uebernommen.' } if (-not [string]::IsNullOrWhiteSpace($actualRelay)) { throw "Kontrolle fehlgeschlagen: Relay-Server ist nicht leer: '$actualRelay'." } if (-not [string]::IsNullOrWhiteSpace($actualApi)) { throw "Kontrolle fehlgeschlagen: API-Server ist nicht leer: '$actualApi'." } Write-Host " OK: ID-Server = $actualServer" -ForegroundColor Green Write-Host ' OK: Key wurde von RustDesk gespeichert.' -ForegroundColor Green Write-Host ' OK: Relay-Server und API-Server sind leer.' -ForegroundColor Green } function Enable-RustDeskAutostart { param([Parameter(Mandatory = $true)][string]$Exe) $profile = Get-InteractiveProfile $startupFolder = Join-Path $profile 'AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' New-Item -Path $startupFolder -ItemType Directory -Force | Out-Null $shortcutPath = Join-Path $startupFolder 'RustDesk.lnk' $shell = New-Object -ComObject WScript.Shell $shortcut = $shell.CreateShortcut($shortcutPath) $shortcut.TargetPath = $Exe $shortcut.WorkingDirectory = Split-Path -Parent $Exe $shortcut.WindowStyle = 1 $shortcut.Save() if (-not (Test-Path -LiteralPath $shortcutPath -PathType Leaf)) { throw 'Der automatische Start von RustDesk konnte nicht eingerichtet werden.' } Write-Host " OK: Autostart eingerichtet: $shortcutPath" -ForegroundColor Green } function Start-RustDeskForInteractiveUser { param([Parameter(Mandatory = $true)][string]$Exe) Write-Step 'Starte RustDesk sichtbar fuer den angemeldeten Benutzer.' $explorer = Get-Process -Name 'explorer' -ErrorAction SilentlyContinue | Sort-Object StartTime | Select-Object -First 1 if ($explorer) { # Explorer startet das Programm in der bereits angemeldeten Benutzer-Sitzung. Start-Process -FilePath (Join-Path $env:WINDIR 'explorer.exe') -ArgumentList ('"{0}"' -f $Exe) | Out-Null $sessionId = $explorer.SessionId $deadline = (Get-Date).AddSeconds(20) do { Start-Sleep -Seconds 2 $visibleProcess = Get-Process -Name 'RustDesk' -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId } | Select-Object -First 1 if ($visibleProcess) { Write-Host ' OK: RustDesk wurde in der Benutzer-Sitzung gestartet.' -ForegroundColor Green return } } while ((Get-Date) -lt $deadline) } else { Start-Process -FilePath $Exe | Out-Null Start-Sleep -Seconds 5 if (Get-Process -Name 'RustDesk' -ErrorAction SilentlyContinue) { Write-Host ' OK: RustDesk wurde gestartet.' -ForegroundColor Green return } } throw 'RustDesk wurde installiert, konnte aber nicht sichtbar gestartet werden.' } function Uninstall-OldRustDesk { Stop-RustDesk $entries = @(Get-UninstallEntries) $exe = Get-RustDeskExe -Entries $entries if ($exe) { Write-Step "Deinstalliere die alte Version: $exe --uninstall" Start-Process -FilePath $exe -ArgumentList '--uninstall' -Wait Start-Sleep -Seconds 5 } else { foreach ($entry in $entries) { $uninstallString = [string]$entry.UninstallString if ($uninstallString -match '\{[0-9A-Fa-f-]{36}\}') { $productCode = $Matches[0] Write-Step "Deinstalliere MSI-Paket: $productCode" Start-Process -FilePath 'msiexec.exe' -ArgumentList "/x $productCode /qn /norestart" -Wait } } } Stop-RustDesk if (Get-Service -Name 'RustDesk' -ErrorAction SilentlyContinue) { & sc.exe stop RustDesk | Out-Null & sc.exe delete RustDesk | Out-Null Start-Sleep -Seconds 2 } $profile = Get-InteractiveProfile Remove-Folder -Path (Join-Path $profile 'AppData\Roaming\RustDesk') Remove-Folder -Path (Join-Path $env:WINDIR 'ServiceProfiles\LocalService\AppData\Roaming\RustDesk') Remove-Folder -Path (Join-Path $env:WINDIR 'ServiceProfiles\NetworkService\AppData\Roaming\RustDesk') if ($env:ProgramFiles) { Remove-Folder -Path (Join-Path $env:ProgramFiles 'RustDesk') } if (${env:ProgramFiles(x86)}) { Remove-Folder -Path (Join-Path ${env:ProgramFiles(x86)} 'RustDesk') } foreach ($entry in @(Get-UninstallEntries)) { if ($entry.PSPath) { Remove-Item -LiteralPath $entry.PSPath -Recurse -Force -ErrorAction SilentlyContinue } } } function Install-NewRustDesk { Write-Step 'Installiere den neuen vorkonfigurierten RustDesk-Client.' $installerProcess = Start-Process -FilePath $InstallerPath -ArgumentList '--silent-install' -PassThru $deadline = (Get-Date).AddSeconds(120) $service = $null do { Start-Sleep -Seconds 2 $service = Get-Service -Name 'RustDesk' -ErrorAction SilentlyContinue if ($null -ne $service) { break } } while ((Get-Date) -lt $deadline) if ($null -eq $service) { Stop-Process -Id $installerProcess.Id -Force -ErrorAction SilentlyContinue throw 'Die Neuinstallation war nach 120 Sekunden nicht erfolgreich: RustDesk-Dienst fehlt.' } if (-not $installerProcess.HasExited) { [void]$installerProcess.WaitForExit(30000) } if (-not $installerProcess.HasExited) { Stop-Process -Id $installerProcess.Id -Force -ErrorAction SilentlyContinue } Start-Sleep -Seconds 3 $service = Get-Service -Name 'RustDesk' -ErrorAction SilentlyContinue if ($service.Status -ne 'Running') { Start-Service -Name 'RustDesk' Start-Sleep -Seconds 3 } $newExe = Get-RustDeskExe -Entries @(Get-UninstallEntries) if (-not $newExe) { throw 'RustDesk.exe wurde nach der Installation nicht gefunden.' } Write-Step 'Bereite den neuen RustDesk-Dienst fuer die Konfiguration vor.' Stop-RustDesk Set-Service -Name 'RustDesk' -StartupType Automatic Start-Service -Name 'RustDesk' Start-Sleep -Seconds 3 Set-RustDeskServerConfiguration -Exe $newExe Restart-Service -Name 'RustDesk' -Force Start-Sleep -Seconds 5 # Nach dem Neustart nochmals aus RustDesk selbst auslesen. $verifiedServer = Invoke-RustDeskCli -Exe $newExe -Arguments @('--option', 'custom-rendezvous-server') $verifiedKey = Invoke-RustDeskCli -Exe $newExe -Arguments @('--option', 'key') $verifiedRelay = Invoke-RustDeskCli -Exe $newExe -Arguments @('--option', 'relay-server') if ($verifiedServer -ne $ServerIp -or $verifiedKey -ne $PublicKey) { throw 'ID-Server oder Key sind nach dem Dienstneustart nicht mehr korrekt gespeichert.' } if (-not [string]::IsNullOrWhiteSpace($verifiedRelay)) { throw "Der Relay-Server sollte leer sein, enthaelt aber '$verifiedRelay'." } Write-Host ' OK: ID-Server und Key sind dauerhaft gespeichert; Relay-Server bleibt leer.' -ForegroundColor Green $newId = '' for ($attempt = 1; $attempt -le 6; $attempt++) { try { $newId = Invoke-RustDeskCli -Exe $newExe -Arguments @('--get-id') -TimeoutSeconds 15 } catch { $newId = '' } if ($newId) { break } Start-Sleep -Seconds 5 } if ($newId) { Write-Host "Neue RustDesk-ID: $newId" -ForegroundColor Green } else { Write-Warning 'Die Serverdaten wurden gesetzt. Die neue ID erscheint nach kurzer Zeit im RustDesk-Fenster.' } Enable-RustDeskAutostart -Exe $newExe Start-RustDeskForInteractiveUser -Exe $newExe Remove-Item -LiteralPath $InstallerPath -Force -ErrorAction SilentlyContinue } Write-Host '' Write-Host "RustDesk-Wechselprogramm v$Version" -ForegroundColor Yellow Write-Host 'Der neue Client wird zuerst heruntergeladen. Danach wird die aktive RustDesk-Verbindung getrennt.' -ForegroundColor Yellow Write-Host '' $confirmation = Read-Host 'Zum Starten bitte JA eingeben' if ($confirmation -cne 'JA') { Write-Host 'Abgebrochen. Es wurde nichts veraendert.' -ForegroundColor Yellow if ($TranscriptStarted) { Stop-Transcript | Out-Null } Read-Host 'Eingabetaste druecken' exit 0 } try { Download-Installer Uninstall-OldRustDesk Install-NewRustDesk Write-Host '' Write-Host 'ERFOLG: RustDesk wurde bereinigt und neu installiert.' -ForegroundColor Green Write-Host 'Ein Windows-Neustart ist nicht erforderlich.' -ForegroundColor Green Write-Host "Protokoll: $LogFile" -ForegroundColor Green } catch { Write-Host '' Write-Host "FEHLER: $($_.Exception.Message)" -ForegroundColor Red Write-Host "Protokoll: $LogFile" -ForegroundColor Red exit 1 } finally { if ($TranscriptStarted) { Stop-Transcript | Out-Null } } Write-Host '' Read-Host 'Zum Schliessen die Eingabetaste druecken'