PowerShell Script To Apply .reg File To Multiple Computers

After our helpdesk imaged almost 100 laptops for remote work, and with about half of them already handed out and in use over our VPN, it was realised the image was suffering from a bug which prevented users from creating/modifying folders on the local drive.

The solution was to apply a .reg fix from the below link, which restored folder file type associations:

https://www.sevenforums.com/attachments/tutorials/260940d1364165567-default-file-type-associations-restore-default_folder.reg

Needing to deploy this to all remote laptops, both internal awaiting deployment and remotely on our VPN, there were a few options:

  1. Group Policy to apply registry changes
  2. A startup/login script to apply the .reg file
  3. A script to apply the .reg file

After encountering some difficulties using Group Policy and login scripts, a quick test of Invoke-Command on a test laptop resulted in immediate success, so I set about creating a small script to target the remaining machines.

While Group Policy/Login Scripts have the advantage of “always on”, I felt a script that ran hourly against a target OU would have a similar effect and be more flexible.

I didn’t want the script to continuously apply the .reg file to laptops that already had the fix applied, so the script maintains a “complete.txt” file; if no error is encountered during the script’s Invoke-Command, the hostname of the machine is written to this text file, and on subsequent runs a check is made to skip these hostnames. The file also acts as a record for manual check of which laptops have been fixed.

Below is the complete script. Write-Host commands are just for some visual feedback during initial runs, and file paths are generic.

$computers = Get-ADComputer -Filter * -SearchBase "OU=Remote Laptops,DC=contoso,DC=com"
$complete = Get-Content \\constoso.com\script\complete.txt

foreach ($comp in $computers) 
{
    $name = $comp.Name
    $error.Clear()

    if($name -notin $complete)
    {
        try
        {
            Invoke-Command -ComputerName $name {reg import \\contoso.com\script\Default_Folder.reg *>&1 |Out-Null}
        }
        catch
        {
            Write-Host "Failed to update $name"
        }

        if (!$error)
        {
            Write-Host "Completed $name"
            Add-Content \\contoso.com\script\complete.txt "$name"
        }
        else
        {
            Write-Host "Failed to update $name"
        }
    }
    else
    {
        Write-Host "$name already done"
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *