Search code examples
powershellregistry

PowerShell Script: Registry Key Does Not Save Upon Creation


I am creating a Powershell script that will check to see if a key exists, if it does not exist, then the script will go and create the key. After the key is created, then the script will create a Dword under each key with the value of one.

I am able to elevate the PowerShell Prompt in the script, and I am able to get confirmation that the keys are created. However, when I go to create the DWord, I get an error saying that the keys I just created do not exist.

I re-wrote the entire Key Creation script, and at this point I cannot figure out why the key will not save. Any help is greatly appreciated.

My Janky Code:

# ------------------------------------------------------------------------------------------------------------------------------------------------
# Gains Elevated Privileges for Powershell 
# ------------------------------------------------------------------------------------------------------------------------------------------------
param([switch]$Elevated)

# Creates a function to get the current Privilages Level in Powershell
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# Checks to see if the terminal is elevated, if it is not it will elevate the session.
if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

'running with full privileges'

# ------------------------------------------------------------------------------------------------------------------------------------------------
# Creates the Test1 and Test2 Keys if they do not exist.
# ------------------------------------------------------------------------------------------------------------------------------------------------

# Declaring Variables
$KeyItems = 
"Test1",
"Test2"

$KeyLocation = "HKLM:/Software/Test/"

# For Each Loop that tests to see if the $Key exists, if it does it continues, if the key does not exist, it creates it.
foreach($KeyItem in $KeyItems){
    # Key Variable created in loop.
    $Key = $KeyLocation+$KeyItem

    # Checks to see if the $Key exists, if it does not it creates the key.
     if (-not(Test-Path -Path $Key))
     {
        New-Item -Path $KeyLocation -Name $KeyName -Force
        Write-Host 'Created New Key: ' $Key
     }

    # If the key exists, the script will let us know that the key already exists.
     else
     {
        Write-Host 'This Key Already Exists:' $Key
     }

 }

# ------------------------------------------------------------------------------------------------------------------------------------------------
# Creates the ScanOnDemand key and sets the Value to 1 which will prompt an On Demand Scan for both the Vulnerability and Inventory Modules 
# ------------------------------------------------------------------------------------------------------------------------------------------------

# Declaring Variables
$DWordName = "TestDWord"

$Locations = 
"HKLM:/Software/Test/Test1",
"HKLM:/Software/Test/Test2"

# For Each Loop that will create the DWord and assign it the vale of '1'.
foreach($Location in $Locations){

    # Checks to see if the DWord exists
    try {Get-ItemPropertyValue -Path $Location -Name $DWordName}

    # Creates the DWord with the value of 1. 
    catch {New-ItemProperty -Path $Location -Name $DWordName -Value "1" -Type "Dword"}

}

Solution

  • Hello and Welcome to "User Error: The Musical". I will be your Lead Idiot today.

    I narrowed down the issue to existing in the block of code that creates the Key, not the block that updates the DWord. When I ran the code, I got the following error: New-Item : A key in this path already exists. so I knew that the issue most likely was in the New-Item section.

    I partially-correctly assumed that it was an issue with the variables that I used. I tried to change how the variables were implemented, and even tried every quotation mark combination around my variables in the New-Item section, but I was getting no luck. In an act of desperation I deleted my variables, and hard coded in the location; and it worked.

    While inspecting why hard coding worked and the variables did not, I noticed the error. I used $KeyName as the variable in the New-Item section instead of $KeyItem which I had updated it to because of potential conflicts later.

    My apologies for wasting your time with my mismatched variables, and thank you @AbrahamZinala and @mklement0 for your help, the code works now.

    Below is the working code for reference:

    # ------------------------------------------------------------------------------------------------------------------------------------------------
    # Gains Elevated Privileges for Powershell 
    # ------------------------------------------------------------------------------------------------------------------------------------------------
    param([switch]$Elevated)
    
    # Creates a function to get the current Privilages Level in Powershell
    function Test-Admin {
        $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
        $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
    }
    
    # Checks to see if the terminal is elevated, if it is not it will elevate the session.
    if ((Test-Admin) -eq $false)  {
        if ($elevated) {
            # tried to elevate, did not work, aborting
        } else {
            Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
        }
        exit
    }
    
    'running with full privileges'
    
    # ------------------------------------------------------------------------------------------------------------------------------------------------
    # Creates the Test1 and Test2 Keys if they do not exist.
    # ------------------------------------------------------------------------------------------------------------------------------------------------
    
    # Declaring Variables
    $KeyItems = 
    "Test1",
    "Test2"
    
    $KeyLocation = "HKLM:\Software\Test\"
    
    # For Each Loop that tests to see if the $Key exists, if it does it continues, if the key does not exist, it creates it.
    foreach($KeyItem in $KeyItems){
        # Key Variable created in loop.
        $Key = $KeyLocation+$KeyItem
    
        # If the key exists, the script will let alert. 
        if (Test-Path "$Key")
         {
            Write-Host 'Value Already Exists.'
         }
    
         # Checks to see if the $Key exists, if it does not it creates the key.
         else
         {
            New-Item -Path $KeyLocation -Name $KeyItem
            Write-Host 'Created New Key:' $Key
         }
    
     }
    
    # ------------------------------------------------------------------------------------------------------------------------------------------------
    # Creates the TestDWord key and sets the Value to 1
    # ------------------------------------------------------------------------------------------------------------------------------------------------
    
    # Declaring Variables
    $DWordName = "TestDWord"
    
    $Locations = 
    "HKLM:\Software\Test\Test1",
    "HKLM:\Software\Test\Test2"
    
    # For Each Loop that will create the DWord and assign it the vale of '1'.
    foreach($Location in $Locations){
    
        # Checks to see if the DWord exists
        try {Get-ItemPropertyValue -Path $Location -Name $DWordName}
    
        # Creates the DWord with the value of 1. 
        catch {New-ItemProperty -Path $Location -Name $DWordName -Value "1" -Type "Dword" -ErrorAction Stop}
    
    }