Trying to delete a reg key in PowerShell as a PS command in MDT.

Rick Someone 411 Reputation points
2021-12-15T13:49:17.013+00:00

I'm trying to delete a 'value' of a key in the registry IF it exists. I don't know the action to script if it doesn't exist.

I can run this and it does remove the value if its there, but errors out when the value is not there.

The PS I added to MDT is:

Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Keyname -Name "GUID"
Remove-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Keyname" -Name "GUID" -ErrorAction Ignore

I want to remove the GUID entry within the key, if it sees it. What is the syntax to just do nothing if it doesn't see it?

Windows for business Windows Client for IT Pros Devices and deployment Set up, install, or upgrade
{count} votes

3 answers

Sort by: Most helpful
  1. Rick Someone 411 Reputation points
    2021-12-17T13:54:40.983+00:00

    This is what worked:

    $Path = 'HKLM:\SOFTWARE\WOW6432Node\mykey'
    $Name = 'GUID'
    
        Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore
        Remove-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore
    
    5 people found this answer helpful.

  2. AllenLiu-MSFT 49,311 Reputation points Microsoft External Staff
    2021-12-16T07:16:08.437+00:00

    Hi, @Rick Someone
    Thank you for posting in Microsoft Q&A forum.

    You may replace your PS script with this:

    function Test-RegistryValue {  
      
    param (  
      
     [parameter(Mandatory=$true)]  
     [ValidateNotNullOrEmpty()]$Path,  
      
    [parameter(Mandatory=$true)]  
     [ValidateNotNullOrEmpty()]$Value  
    )  
      
    try {  
      
    Get-ItemProperty -Path $Path -Name $Value -ErrorAction Stop | Out-Null  
     return $true  
     }  
      
    catch {  
      
    return $false  
      
    }  
    }  
      
      
    if (Test-RegistryValue -Path 'HKLM:\SOFTWARE\WOW6432Node\Keyname' -value 'GUID')  
    {Remove-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\Keyname' -Name GUID}  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    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. Rick Someone 411 Reputation points
    2021-12-17T13:53:51.497+00:00

    This worked without error:

    $Path = 'HKLM:\SOFTWARE\WOW6432Node\mykey'
    $Name = 'GUID'
    
        Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore
        Remove-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore
    
    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.