PowerShell Gallery | Functions/Set-RegistryKeyValue.ps1 2.3.0 (2024)

Functions/Set-RegistryKeyValue.ps1

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

functionSet-RegistryKeyValue
{
<#
.SYNOPSIS
Sets a value in a registry key.

.DESCRIPTION
The `Set-RegistryKeyValue` function sets the value of a registry key. If the key doesn't exist, it is created first. Uses PowerShell's `New-ItemPropery` to create the value if doesn't exist. Otherwise uses `Set-ItemProperty` to set the value.

`DWord` and `QWord` values are stored in the registry as unsigned integers. If you pass a negative integer for the `DWord` and `QWord` parameters, PowerShell will convert it to an unsigned integer before storing. You won't get the same negative number back.

To store integer values greater than `[Int32]::MaxValue` or `[Int64]::MaxValue`, use the `UDWord` and `UQWord` parameters, respectively, which are unsigned integers. These parameters were in Carbon 2.0.

In versions of Carbon before 2.0, you'll need to convert these large unsigned integers into signed integers. You can't do this with casting. Casting preservers the value, not the bits underneath. You need to re-interpret the bits. Here's some sample code:

# Carbon 1.0
$bytes = [BitConverter]::GetBytes( $unsignedInt )
$signedInt = [BitConverter]::ToInt32( $bytes, 0 ) # Or use `ToInt64` if you're working with 64-bit/QWord values
Set-RegistryKeyValue -Path $Path -Name 'MyUnsignedDWord' -DWord $signedInt

# Carbon 2.0
Set-RegistryKeyValue -Path $Path -Name 'MyUnsignedDWord' -UDWord $unsignedInt

.LINK
Get-RegistryKeyValue

.LINK
Test-RegistryKeyValue

.EXAMPLE
Set-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test -Name Status -String foobar

Creates the `Status` string value under the `hklm:\Software\Carbon\Test` key and sets its value to `foobar`.

.EXAMPLE
Set-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test -Name ComputerName -String '%ComputerName%' -Expand

Creates an expandable string. When retrieving this value, environment variables will be expanded.

.EXAMPLE
Set-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test -Name Movies -String ('Signs','Star Wars','Raiders of the Lost Ark')

Sets a multi-string (i.e. array) value.

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'SomeBytes' -Binary ([byte[]]@( 1, 2, 3, 4))

Sets a binary value (i.e. `REG_BINARY`).

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'AnInt' -DWord 48043

Sets a binary value (i.e. `REG_DWORD`).

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'AnInt64' -QWord 9223372036854775807

Sets a binary value (i.e. `REG_QWORD`).

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'AnUnsignedInt' -UDWord [uint32]::MaxValue

Demonstrates how to set a registry value with an unsigned integer or an integer bigger than `[int]::MaxValue`.

The `UDWord` parameter was added in Carbon 2.0. In earlier versions of Carbon, you have to convert the unsigned int's bits to a signed integer:

$bytes = [BitConverter]::GetBytes( $unsignedInt )
$signedInt = [BitConverter]::ToInt32( $bytes, 0 )
Set-RegistryKeyValue -Path $Path -Name 'MyUnsignedDWord' -DWord $signedInt

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'AnUnsignedInt64' -UQWord [uint64]::MaxValue

Demonstrates how to set a registry value with an unsigned 64-bit integer or a 64-bit integer bigger than `[long]::MaxValue`.

The `UQWord parameter was added in Carbon 2.0. In earlier versions of Carbon, you have to convert the unsigned int's bits to a signed integer:

$bytes = [BitConverter]::GetBytes( $unsignedInt )
$signedInt = [BitConverter]::ToInt64( $bytes, 0 )
Set-RegistryKeyValue -Path $Path -Name 'MyUnsignedDWord' -DWord $signedInt

.EXAMPLE
Set-RegistryKeyValue -Path hklm:\Software\Carbon\Test -Name 'UsedToBeAStringNowShouldBeDWord' -DWord 1 -Force

Uses the `Force` parameter to delete the existing `UsedToBeAStringNowShouldBeDWord` before re-creating it. This flag is useful if you need to change the type of a registry value.
#>

[CmdletBinding(SupportsShouldPRocess=$true,DefaultParameterSetName='String')]
param(
[Parameter(Mandatory=$true)]
[string]
# The path to the registry key where the value should be set. Will be created if it doesn't exist.
$Path,

[Parameter(Mandatory=$true)]
[string]
# The name of the value being set.
$Name,

[Parameter(Mandatory=$true,ParameterSetName='String')]
[AllowEmptyString()]
[AllowNull()]
[string]
# The value's data. Creates a value for holding string data (i.e. `REG_SZ`). If `$null`, the value will be saved as an empty string.
$String,

[Parameter(ParameterSetName='String')]
[Switch]
# The string should be expanded when retrieved. Creates a value for holding expanded string data (i.e. `REG_EXPAND_SZ`).
$Expand,

[Parameter(Mandatory=$true,ParameterSetName='Binary')]
[byte[]]
# The value's data. Creates a value for holding binary data (i.e. `REG_BINARY`).
$Binary,

[Parameter(Mandatory=$true,ParameterSetName='DWord')]
[int]
# The value's data. Creates a value for holding a 32-bit integer (i.e. `REG_DWORD`).
$DWord,

[Parameter(Mandatory=$true,ParameterSetName='DWordAsUnsignedInt')]
[uint32]
# The value's data as an unsigned integer (i.e. `UInt32`). Creates a value for holding a 32-bit integer (i.e. `REG_DWORD`).
$UDWord,

[Parameter(Mandatory=$true,ParameterSetName='QWord')]
[long]
# The value's data. Creates a value for holding a 64-bit integer (i.e. `REG_QWORD`).
$QWord,

[Parameter(Mandatory=$true,ParameterSetName='QWordAsUnsignedInt')]
[uint64]
# The value's data as an unsigned long (i.e. `UInt64`). Creates a value for holding a 64-bit integer (i.e. `REG_QWORD`).
$UQWord,

[Parameter(Mandatory=$true,ParameterSetName='MultiString')]
[string[]]
# The value's data. Creates a value for holding an array of strings (i.e. `REG_MULTI_SZ`).
$Strings,

[Switch]
# Removes and re-creates the value. Useful for changing a value's type.
$Force,

[Parameter(DontShow=$true)]
[Switch]
# OBSOLETE. Will be removed in a future version of Carbon.
$Quiet
)

Set-StrictMode-Version'Latest'

Use-CallerPreference-Cmdlet$PSCmdlet-Session$ExecutionContext.SessionState

if($PSBoundParameters.ContainsKey('Quiet'))
{
Write-Warning('Set-RegistryKeyValue''s -Quiet switch is obsolete and will be removed in a future version of Carbon. Please remove usages.')
}

$value=$null
$type=$pscmdlet.ParameterSetName
switch-Exact($pscmdlet.ParameterSetName)
{
'String'
{
$value=$String
if($Expand)
{
$type='ExpandString'
}
}
'Binary'{$value=$Binary}
'DWord'{$value=$DWord}
'QWord'{$value=$QWord}
'DWordAsUnsignedInt'
{
$value=$UDWord
$type='DWord'
}
'QWordAsUnsignedInt'
{
$value=$UQWord
$type='QWord'
}
'MultiString'{$value=$Strings}
}

Install-RegistryKey-Path$Path

if($Force)
{
Remove-RegistryKeyValue-Path$Path-Name$Name
}

if(Test-RegistryKeyValue-Path$Path-Name$Name)
{
$currentValue=Get-RegistryKeyValue-Path$Path-Name$Name
if($currentValue-ne$value)
{
Write-Verbose-Message("[{0}@{1}] {2} -> {3}'"-f$Path,$Name,$currentValue,$value)
Set-ItemProperty-Path$Path-Name$Name-Value$value
}
}
else
{
Write-Verbose-Message("[{0}@{1}] -> {2}'"-f$Path,$Name,$value)
$null=New-ItemProperty-Path$Path-Name$Name-Value$value-PropertyType$type
}
}

PowerShell Gallery
        | Functions/Set-RegistryKeyValue.ps1 2.3.0 (2024)

FAQs

PowerShell Gallery | Functions/Set-RegistryKeyValue.ps1 2.3.0? ›

The `Set-RegistryKeyValue` function sets the value of a registry key. If the key doesn't exist, it is created first. Uses PowerShell's `New-ItemPropery` to create the value if doesn't exist. Otherwise uses `Set-ItemProperty` to set the value.

How to set registry value in PowerShell? ›

Creating a Registry Key Using PowerShell
  1. New-Item -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication" ...
  2. $Key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MyApp" If(Test-Path -Path "Registry::$Key") { Write-host -f Green "Key Exists!" } Else { Write-host -f Yellow "Key doesn't Exists!" }
Jun 8, 2024

How to check if registry key is set in PowerShell? ›

You can use the Get-ItemProperty cmdlet to retrieve the value of a registry key, and then use an if statement to check the value. This script retrieves the value of the Connected registry key from the specified path, and then checks if the value is equal to "1".

How to create dword value in registry using PowerShell? ›

Scenario 1
  1. $RegistryPath = 'HKCU:\Software\Test\MyKey' $Name = 'Version' $Value = '12' New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force Copy. ...
  2. New-ItemProperty : Cannot find path 'HKCU:\Software\Test\MyKey' because it does not exist.
Nov 23, 2023

Which PowerShell cmdlet is used to modify a registry key value? ›

You can also use the New-ItemProperty cmdlet to create the registry entry and its value and then use Set-ItemProperty to change the value.

Top Articles
How and why do we pay bitcoin miner fees?
Rust Developer Salary - Sep 2024
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 6547

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.