powershellregistrycustom-actionvs-installer-project

Cannot find registry path running a powershell script as a custom action


I have a PowerShell script where I am reading and editing registry.

I tried running it manually, calling it from command line, converting it to an .exe with ps2exe, and for all of those scenarios it works as intended. However, when I package it with my installer (using MS Visual Studio Installer Projects) and try running it as Custom Actions/Commit/script.exe, it suddenly cannot find the registry keys.

Here's a snippet of my script.

## initializing new variables
$req_path = Get-Item -Path "HKCU:\SOFTWARE\Microsoft\Office\16.0\Excel\Options" |
  Select-Object -ExpandProperty Property
echo $req_path
ERROR: Get-Item : Cannot find path
'HKCU:\SOFTWARE\Microsoft\Office\16.0\Excel\Options' because it doesnot exist.

I have also tried this variation to no avail:

$req_path = Get-Item -Path Registry::HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\Options |
  Select-Object -ExpandProperty Property

Since this is part of the installer, it runs as admin, so privileges are not the culprit.

So, How can I access the registry keys when running a PowerShell script as a custom action?

Some additional info.:


Solution

  • Considering that I am not an expert in , there is a great chance that there is a better way or at least my implementation is not the most efficient one, but I found a way.

    ## HKCU is not accessible when running the script from nt\ authority system
    ## Hence, accessing the HKU/SID for the current user
    ## finding current user's SID
    ## list of profiles
    $profileIP = 
    (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*") | 
    Select-Object ProfileImagePath
    $profileIP = $profileIP.ProfileImagePath
    
    ## list of SIDs
    $SIDs = 
    (Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\") | 
    Select-Object Name 
    $SIDs = (Split-Path $SIDs -Leaf).Trim("{}")
    
    ## finding the SID for the current user
    $sid_index = 0
    
    foreach ($entry in $profileIP) {
        if ($entry.ToString().ToUpper().Contains($env:USERNAME.ToUpper())){break}
        $sid_index += 1
    }
    
    $CU_SID = $SIDs[$sid_index]
    
    ## initiating HKU for this instance of powershell
    New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
    
    ## Get items under SOFTWARE\Microsoft\Office\16.0\Excel\Options
    $req_ref = -join @("HKU:\",$CU_SID,"\SOFTWARE\Microsoft\Office\16.0\Excel\Options")
    $req_path = Get-Item -Path $req_ref |
      Select-Object -ExpandProperty Property