Script to Change Reg Value on Remote Machines

Param(
[Parameter(mandatory, HelpMessage = "Enter ComputerName")]
[string]$ComputerName,
[Parameter(mandatory, HelpMessage = "Enter Reboot Day")]
[string]$RebootDay,
$RegistryPath = "HKLM:\SOFTWARE\WOW6432Node\GSA Reboot"
)

IF (Invoke-Command -ComputerName $ComputerName {Test-Path -Path "HKLM:\SOFTWARE\WOW6432Node\GSA Reboot"})
{
Invoke-Command -ComputerName $ComputerName {
Set-ItemProperty -Path $RegistryPath  -Name "Rebootday" -Value $Rebootday} 
}
else
{
Write-Warning "Failed"
}


Read-Host -Prompt "Press Enter to exit"

 

Hi all. I’m learning my way through PowerShell and decided to write a little script to speed up a certain task.

I want to be able to change a value of a Registry key. I want to have it dynamic so anyone of us can simply enter the PC name and the value change. I tried to do this with a $variable. But encountering issues.

I was able to figure out how to do this on a one liner. but running into issues when incorporating it into the script w/ variables in the param block…

If I run the above script. Nothing happens. If I replace $RegistryPath with the actual path (“HKLM:\SOFTWARE\WOW6432Node\GSA Reboot”). And then replace $Rebootday with (let’s say) Saturday. The value gets changed.

If I only replace “$RegistryPath” with the manual path and leave in the $Rebootday, it simply blanks out the Value in the XYZ Computer…

I don’t understand how/why variables will not work, in a script like this…

Thank you for any guidance.

The variable only exists locally, the remote computers don’t have those variables. Either assign them in the scriptblock so they are defined on the remote systems or change the variables inside the remote scriptblock to $using:variable format.

$using:RegistryPath
$using:Rebootday

I’d recommend to start small, test these small things and add stuff when these small things work as expected. :wink: You have a scope issue in your code. A scriptblock does not know about variables outside of the scriptblock. You have to use a param block or the scope modifier USING. Like this:

Param(
    [Parameter(mandatory, HelpMessage = 'Enter ComputerName')]
    [string]$ComputerName,
    [Parameter(mandatory, HelpMessage = 'Enter Reboot Day')]
    [string]$RebootDay,
    $RegistryPath = 'registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GSA Reboot'
)

if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) {
    Invoke-Command -ComputerName $ComputerName {
        if (-not (Test-Path -Path $USING:RegistryPath)) {
            New-Item -Path $USING:RegistryPath -ItemType Directory | Out-Null
            Set-ItemProperty -Path $USING:RegistryPath -Name 'Rebootday' -Value $USING:Rebootday -Force
        }
        else {
            Set-ItemProperty -Path $USING:RegistryPath -Name 'Rebootday' -Value $USING:Rebootday -Force
        }
    }
}

This is great and it makes sense! Thanks for the revision. I see what I did wrong…