powershellpowershell-remotingregistrykey

Change value in registry on multiple servers using credentials


Looking to enable reg key on multiple remote machines. Attempt 1:

$Servers = Get-Content "C:\PowerShell\TestServers.txt"
$Path = "HKLM:\SYSTEM\CurrentControlSet\Services\"
$Property = "*REG_WORD NAME*"
$Value = "1"

Foreach ($Server in $Servers) 
{
  Set-ItemProperty -Path $Path -Name $Property -Value $Value
}

Error: Set-ItemProperty : Requested registry access is not allowed. NOTE: checked effective access, the account being used has FULLControl over the specific hive Attempt 2: Created a function, added the get-credential cmdlet

function Set-RemoteRegistryValue {
    param (
        $ComputerName,
        $Path,
        $Name,
        $Value,
        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = [System.Management.Automation.PSCredential]::Empty
    )
    
        $null = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
            Set-ItemProperty -Path $using:Path -Name $using:Name -Value $using:Value
        } -Credential $Credential
}

I am now able to call the function and set the reg key value as desired, but only one machine at a time:

$remoteKeyParams = @{
    ComputerName ='name' 
    Path = "HKLM:\SYSTEM\CurrentControlSet\Services\"
    Name = "*keyname*"
    Value = "1"
}
    Set-RemoteRegistryValue @remoteKeyParams -Credential (Get-Credential)    

I have tried putting multiple machines in as a string, and a text file:

[string]$ComputerName = "name","name","name"
 ComputerName = c:\temp\testservers.txt

Am I doing something very wrong here?


Solution

  • Confirm you have one server per line and then this is how you should write it.

    $Servers = Get-Content "C:\PowerShell\TestServers.txt"
    $Path = "HKLM:\SYSTEM\CurrentControlSet\Services\"
    $Property = "*REG_WORD NAME*"
    $Value = "1"
    
    Invoke-Command -ComputerName $servers -ScriptBlock {
                Set-ItemProperty -Path $using:Path -Name $using:Name -Value $using:Value
            } -Credential $Credential
    

    When you pass all the server names to Invoke-Command it will run them all asynchronously (up to 32 by default on 5.1)