Windows Remote Registry Backup


Time for another code snippet. Had to take some registry backups for a rollback plan and here I am with a PowerShell script that enables to backup registry hives from remote computers. I am still in search of a better and easier method as the method which I used makes a lot of assumptions and copying of files here and there. Some interesting points I have to take care when I wrote this script was regarding the encoding in out-file cmdlet and argument passing in an invoke-command script block. Please feel free to add in your suggestions.


Function Export-RemoteRegistry()
{
<#
.SYNOPSIS
Enables to backup/Export registry hives from remote servers.
.DESCRIPTION
Enbles to create backup of registry hives from remote servers and copy it to a centralized location.
User needs to have admin privilages to the system and registry keys.
.PARAMETER ComputerName
Accepts a computer name or IP addresse.
.PARAMETER Key
Registry key value which needs to exported.
.EXAMPLE
Export-RemoteRegistry -Key HKLM\SOFTWARE\MICROSOFT\DFS -ShareLocation D:\RegBackup -ComputerName SERVER1
.LINK
https://posh-scripting.blogspot.in/2016/10/memory-usage.html
#>
[CmdletBinding()]
param
(
[Parameter (Position = 1, Mandatory = $True, HelpMessage = 'Registry key which needs to backed up.')]
[String]$Key,
[Parameter (Position = 2, Mandatory = $True, HelpMessage = "Share location to store the backup of registry keys.")]
[String]$ShareLocation,
[Parameter (Position = 3, Mandatory = $False, HelpMessage = "The computer name, default is local host.")]
[String]$ComputerName = $env:COMPUTERNAME
)
$flattenedKey = $Key -replace "\\","_" # For the purpose of backup file naming
$remoteLoc = "\\$ComputerName\C$\Windows\Temp"
$command = "reg export $key $remoteLoc\$ComputerName`_$flattenedKey.reg /y"
$batfileName = "regExport.bat"
$batFileLoc = "$remoteLoc\$batfileName"
$command | Out-File $batFileLoc -Encoding default # Ecoding 
#has to be done in in ANSI format to avaoid special character related errors.
$session = New-PSSession -ComputerName $ComputerName
$execBat = {
param($batFileLoc)
cmd.exe /c $batFileLoc
}
$remoteJob = Invoke-Command -Session $session -ScriptBlock $execBat -ArgumentList $batFileLoc -AsJob
$remoteJob | Wait-Job # Waits till remote job completes
Remove-Item -Path "$remoteLoc\$batfileName" -Force
Start-Sleep -Seconds 2
Copy-Item -Path "$remoteLoc\$ComputerName`_$flattenedKey.reg" -Destination $ShareLocation -Force # provide
Remove-Item -Path "$remoteLoc\$ComputerName`_$flattenedKey.reg"
Remove-PSSession -Session $session
}

Comments

Post a Comment

Popular posts from this blog

Check SQL Server Database Status

PowerShell and Azure Resource Graph

Static Code Analysis: Some Tools