Greg Bray
Greg Bray

Reputation: 15757

Set Binary Registry Key to GUID Value using Powershell or Powershell Desired State Configuration

We were instructed to update a REG_BINARY registry key using a GUID value, but we want to do this using PowerShell or PowerShell DSC so it can be automated. The end result should look like this:

REG_BINARY key set to GUID value

As that is the hex representation of the GUID:

GUID: {01234567-89AB-CDEF-0123-456789ABCDEF}
Hex:  67-45-23-01-AB-89-EF-CD-01-23-45-67-89-AB-CD-EF

Upvotes: 1

Views: 1472

Answers (1)

Greg Bray
Greg Bray

Reputation: 15757

The following will create a new binary key using PowerShell

$value = [guid]::Parse('01234567-89AB-CDEF-0123-456789ABCDEF')
$path = 'HKLM:Software\Company\Product'
New-ItemProperty -Path $path -Name MyGUIDKey -PropertyType Binary -Value $value.ToByteArray()

If the key already exists you can update it's value by replacing the last line with

Set-ItemProperty -Path $path -Name MyGUIDKey -Value $value.ToByteArray()

If you want to create or update they key using PowerShell DSC your configuration should look like:

Registry SetBinaryKeyToGuidValue
{
    Key = 'HKEY_LOCAL_MACHINE\Software\Company\Product'
    ValueName = 'MyGUIDKey'
    ValueData =  @([BitConverter]::ToString([guid]::Parse('01234567-89AB-CDEF-0123-456789ABCDEF').ToByteArray()).Replace("-", [String]::Empty))
    ValueType = 'Binary'
}

The ValueData is very particular about what format is used, and it should be and Array of Hex strings like: @('001122FF'). If you use any other format you will get an error message like:

PowerShell DSC resource MSFT_RegistryResource failed to execute Set-TargetResource functionality with error message: (ERROR) Parameter 'ValueData' has an invalid value '01234567-89AB-CDEF-0123-456789ABCDEF' for type 'Binary'

Upvotes: 3

Related Questions