Powershell script to check for registry key and create if not exist

Nadimuddin J Shaikh 1 Reputation point
2022-06-24T14:31:06.19+00:00

I am a little stuck with the below requirement
Would appreciate some help from any of you script experts

I need a PowerShell script to check for a registry key and create it if it does not exist
Also to check for a registry key and create it if it does not exist
Finally also to check for a registry key value and create it if it does not exist

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,576 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Ian Xue 38,381 Reputation points Microsoft Vendor
    2022-06-27T09:04:19.477+00:00

    Hi @Nadimuddin J Shaikh ,

    The Get-ItemProperty cmdlet can check registry values for you. To create the value if not found, you can try something like this

    $KeyPath = "HKCU:\Registry\Key\Path"  
    $ValueName = "name"  
    $ValueData = "data"  
    try{  
        Get-ItemProperty -Path $KeyPath -Name $valueName -ErrorAction Stop  
    }  
    catch [System.Management.Automation.ItemNotFoundException] {  
        New-Item -Path $KeyPath -Force  
        New-ItemProperty -Path $KeyPath -Name $ValueName -Value $ValueData -Force  
    }  
    catch {  
        New-ItemProperty -Path $KeyPath -Name $ValueName -Value $ValueData -Type String -Force  
    }  
    

    Best Regards,
    Ian Xue

    -----------------------------

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    3 people found this answer helpful.

  2. Nadimuddin J Shaikh 1 Reputation point
    2022-11-16T05:11:40.87+00:00

    @Brandon Woods - many thanks for the update

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.