From 0cd3d8facb04721f0cd54589b20e198535768ba1 Mon Sep 17 00:00:00 2001 From: allebonvi Date: Thu, 2 Jul 2026 12:50:19 +0200 Subject: [PATCH] Supporta task backup con credenziali memorizzate --- scripts/Register-BakRestTask.ps1 | 51 +++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/scripts/Register-BakRestTask.ps1 b/scripts/Register-BakRestTask.ps1 index a196af0..a432c9f 100644 --- a/scripts/Register-BakRestTask.ps1 +++ b/scripts/Register-BakRestTask.ps1 @@ -7,6 +7,10 @@ param( [switch]$RunAsCurrentUser, + [switch]$RunAsStoredCredentials, + + [string]$UserName, + [switch]$NoShutdown ) @@ -45,6 +49,10 @@ if ($NoShutdown -and $Task -eq "BackupOnLogoff") { $xml = $xml -replace '-m bakrest\.tray_app --nogui', '-m bakrest.tray_app --nogui --no-shutdown' } +if ($RunAsStoredCredentials -and $RunAsCurrentUser) { + throw "Use either -RunAsCurrentUser or -RunAsStoredCredentials, not both." +} + if ($RunAsCurrentUser) { $currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $currentSid = $currentIdentity.User.Value @@ -65,11 +73,48 @@ if ($RunAsCurrentUser) { ) } +$plainPassword = $null +$runAsName = $null +if ($RunAsStoredCredentials) { + if (-not $UserName) { + $UserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name + } + + $securePassword = Read-Host -Prompt "Password for $UserName" -AsSecureString + $passwordPtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword) + try { + $plainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($passwordPtr) + } finally { + [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($passwordPtr) + } + + $principalXml = @" + + + $([System.Security.SecurityElement]::Escape($UserName)) + Password + LeastPrivilege + + +"@ + $xml = [regex]::Replace( + $xml, + '.*?', + $principalXml, + [System.Text.RegularExpressions.RegexOptions]::Singleline + ) + $runAsName = $UserName +} + $tempXml = Join-Path $env:TEMP ("bakrest-task-{0}.xml" -f ([Guid]::NewGuid())) [System.IO.File]::WriteAllText($tempXml, $xml, [System.Text.Encoding]::Unicode) try { - schtasks.exe /Create /TN $taskName /XML $tempXml /F + if ($RunAsStoredCredentials) { + schtasks.exe /Create /TN $taskName /XML $tempXml /RU $UserName /RP $plainPassword /F + } else { + schtasks.exe /Create /TN $taskName /XML $tempXml /F + } if ($LASTEXITCODE -ne 0) { throw "schtasks failed with exit code $LASTEXITCODE" } @@ -79,9 +124,13 @@ try { if ($RunAsCurrentUser) { Write-Host "RunAs: $($currentIdentity.Name)" } + if ($RunAsStoredCredentials) { + Write-Host "RunAs: $runAsName (stored credentials)" + } if ($NoShutdown -and $Task -eq "BackupOnLogoff") { Write-Host "BackupOnLogoff registered in debug mode: --no-shutdown" } } finally { + $plainPassword = $null Remove-Item -LiteralPath $tempXml -Force -ErrorAction SilentlyContinue }