
Below is a PowerShell function that sets a registry value for all users on a Windows machine. This function will iterate through all user profiles and set the specified registry value.
function Set-RegistryValueForAllUsers {
param (
[Parameter(Mandatory = $true)]
[string]$RegistryPath,
[Parameter(Mandatory = $true)]
[string]$ValueName,
[Parameter(Mandatory = $true)]
[string]$ValueData,
[Parameter(Mandatory = $false)]
[Microsoft.Win32.RegistryValueKind]$ValueType = [Microsoft.Win32.RegistryValueKind]::String
)
# Get all user profiles
$userProfiles = Get-WmiObject -Class Win32_UserProfile | Where-Object { $_.Special -eq $false }
foreach ($profile in $userProfiles) {
$userHive = "HKEY_USERS\$($profile.SID)"
$fullRegistryPath = "$userHive\$RegistryPath"
try {
# Create the registry key if it doesn't exist
if (-not (Test-Path -Path $fullRegistryPath)) {
New-Item -Path $fullRegistryPath -Force | Out-Null
}
# Set the registry value
Set-ItemProperty -Path $fullRegistryPath -Name $ValueName -Value $ValueData -Type $ValueType
Write-Output "Successfully set $ValueName to $ValueData for user $($profile.LocalPath)"
} catch {
Write-Error "Failed to set $ValueName for user $($profile.LocalPath): $_"
}
}
}
# Example usage:
# Set-RegistryValueForAllUsers -RegistryPath "Software\MyApp" -ValueName "MySetting" -ValueData "MyValue"
Explanation:
- Parameters:
RegistryPath
: The path to the registry key relative to the user hive.
ValueName
: The name of the registry value to set.
ValueData
: The data to set for the registry value.
ValueType
: The type of the registry value (default isĀ String
).
- Process:
- Retrieves all user profiles usingĀ
Get-WmiObject
.
- Iterates through each user profile and constructs the full registry path.
- Checks if the registry key exists; if not, it creates it.
- Sets the specified registry value for each user profile.