PowerShell / Community-Blog

Submissions for posts to the PowerShell Community Blog -https://devblogs.microsoft.com/powershell-community
MIT License
108 stars 47 forks source link

Update request - Update or Add Registry Key Value with PowerShell #46

Closed mathissuper closed 3 years ago

mathissuper commented 3 years ago

Summary of the update request

doctordns commented 3 years ago

That indeed would make a good candidate article. Of all the providers, I think the registry is the most difficult to grok, at first.

And at the same time, the original post shows one of the things I am pleased we got right on the blog. And that is the formatting of the code in the older blog articles was sub-optimal! We do better and I hope that that is appreciated.

mathissuper commented 3 years ago

Thank you, indeed the formatting of the code in the new blog articles is really appreciated :)
If it could help, here's the function I'm currently using:

function Edit-CompanyRegistry {
  # Adds or edits a registry key whose information is passed as parameters
  # If the key is of type "binary", pass its value in hexadecimal (this function will convert it into binary)
  # Receive the path of the key, its name, type and value
  Param(
    [parameter(Mandatory=$true)] $path,
    [parameter(Mandatory=$true)] $name,
    [parameter(Mandatory=$true)] $type,
    [parameter(Mandatory=$true)] $value
  )
  # If the branch does not exist it is created
  if (!(Test-Path $path)) {
    try { $null = New-Item -Path $path -Force -ErrorAction Stop }
    catch { Write-Host -BackgroundColor DarkRed $Error; exit }
  }
  # If the key is of type "binary", we convert its hexadecimal value into binary
  if ($type -eq 'binary') {
    $hexaValue = $value
    $value = [byte[]](($hexaValue.Split(',')) | % { "0x$_" })
  }
  # Creation of the key if it does not exist, otherwise it is modified
  try { Set-ItemProperty -Path $path -Name $name -Type $type -Value $value }
  catch { Write-Host -BackgroundColor DarkRed $Error; exit }
}

PS: Sorry if my english comments aren't grammatically perfect, it's not my native language and I've simply translate them

doctordns commented 3 years ago

PR #67 addresses this issue.