1

I am trying to modify existing registry key values on remote machines. When I run the following, the targeted registry keys that are supposed to change to the new "AU" instead have their values cleared out.

    $AU = Read-Host -Prompt 'Enter AU "Ex: AU00325"'

    #Changes Registry Keys
    Invoke-Command -ComputerName $Computers -ScriptBlock {

    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;
    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;
    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SYSTEM\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;

}

It looks like the variables aren't carrying over when using invoke command. I verified this by using the -Value "Test" instead of $AU, and that worked fine. Is there a way to make Invoke-Command use variables that are set in previous lines?

DRuppe
  • 109
  • 1
  • 8

1 Answers1

0

You need to pass the variables into the scriptblock using -ArgumentList and then accept them within the scriptblock via param().

Try the following:

$AU = Read-Host -Prompt 'Enter AU "Ex: AU00325"'

#Changes Registry Keys
Invoke-Command -ComputerName $Computers -ScriptBlock {
    param($AU)

    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;
    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;
    New-Item -Path Registry::HKEY_LOCAL_MACHINE\SYSTEM\WFB -Force | New-ItemProperty -Name "Branch" -Value $AU -Force | Out-Null ;

} -ArgumentList $AU
Jacob
  • 1,182
  • 12
  • 18
  • That worked, thanks! – DRuppe Sep 19 '18 at 19:20
  • 2
    @DRuppe An alternative is just using the `$using:` scope. [Read this document](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-5.1) – Maximilian Burszley Sep 19 '18 at 19:53
  • Yikes... Looks like the new registry keys are wiping out all of the other keys in the same folder in all 3 locations... Anybody know why? – DRuppe Sep 20 '18 at 16:30
  • `New-Item` will create a new key and `-Force` will overwrite a key if it exists. If you know the keys exist, then you can use the `-path` parameter on `New-ItemProperty` to just add the required property or change `New-Item` to `Get-Item`. If the keys may not exist then you will need to test their existence before deciding whether to create the key prior to adding the property. If you still can't get it to work let me know and I'll update my answer. – Jacob Sep 20 '18 at 17:16