ninja-one/apply-reg-file.ps1
|
[CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string]$RegistryFileUrl ) function Write-LogMessage { param($Message, [System.ConsoleColor]$Color = 'White') Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): $Message" -ForegroundColor $Color } # Define expected hash - replace with your actual hash $ExpectedHash = "YOUR_EXPECTED_SHA256_HASH_HERE" $HashAlgorithm = "SHA256" try { # Extract filename from URL $fileName = [System.IO.Path]::GetFileName($RegistryFileUrl) if (-not $fileName.EndsWith('.reg')) { throw "URL must point to a .reg file" } # Create temp directory if it doesn't exist $tempDir = Join-Path $env:TEMP "RegFileDownload" if (-not (Test-Path $tempDir)) { New-Item -ItemType Directory -Path $tempDir -Force | Out-Null } $filePath = Join-Path $tempDir $fileName # Check if file already exists if (Test-Path $filePath) { Write-LogMessage "File already exists in temp directory, checking hash..." -Color Yellow $existingHash = (Get-FileHash -Path $filePath -Algorithm $HashAlgorithm).Hash if ($existingHash -eq $ExpectedHash) { Write-LogMessage "Existing file hash matches expected hash" -Color Green } else { Write-LogMessage "Existing file hash does not match, downloading fresh copy..." -Color Yellow Remove-Item -Path $filePath -Force # Download the file $webClient = New-Object System.Net.WebClient $webClient.DownloadFile($RegistryFileUrl, $filePath) } } else { Write-LogMessage "Downloading registry file from $RegistryFileUrl" -Color Cyan # Download the file $webClient = New-Object System.Net.WebClient $webClient.DownloadFile($RegistryFileUrl, $filePath) } # Verify file exists if (-not (Test-Path $filePath)) { throw "Failed to download file" } # Verify file hash $actualHash = (Get-FileHash -Path $filePath -Algorithm $HashAlgorithm).Hash if ($actualHash -ne $ExpectedHash) { throw "File hash verification failed. Expected: $ExpectedHash, Got: $actualHash" } Write-LogMessage "File hash verified successfully" -Color Green # Apply the registry file Write-LogMessage "Applying registry file..." -Color Yellow $process = Start-Process "regedit.exe" -ArgumentList "/s `"$filePath`"" -Wait -PassThru if ($process.ExitCode -ne 0) { throw "Registry import failed with exit code: $($process.ExitCode)" } Write-LogMessage "Registry file applied successfully" -Color Green # Cleanup Remove-Item -Path $filePath -Force Write-LogMessage "Temporary files cleaned up" -Color Green exit 0 } catch { Write-LogMessage "Error: $($_.Exception.Message)" -Color Red # Cleanup on error if (Test-Path $filePath) { Remove-Item -Path $filePath -Force -ErrorAction SilentlyContinue } exit 1 } |