powershellif-statementexistsinvoke-command

Powershell - invoke-command - if reg exists


I have wrote that script but the result is the same for all the computer.To be more precise if my device has the registry Name then all have it which does not reflect the reality.Same if my device does have it. I would need help to understand my mistake. Thank you in advance

$ADSearchBaseComputers = 'ou=computers,ou=xxx,ou=xx,ou=xxx,dc=xx,dc=xxx,dc=xxx'
$computers= get-adcomputer -filter * -searchbase "$ADSearchBaseComputers" | select -Property SamAccountName

foreach ($computer in $computers)
    {
        
        Invoke-Command {    
                            $RegPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
                            $RegName= Get-ItemProperty -Path $RegPath -Name MTBLogin 

                            
                            if  ($RegName)
                             {
                             Write-Output "Reg Key presente pour $($computer.SamAccountName)"
                             
                             }

                            else
                            {
                            Write-Output "Reg Key non presente pour $($computer.SamAccountName)"
                            }
                       }
    
    }

Initially I had the $RegPath and $RegName values before the loop so I moved them inside but the result is the same.


Solution

  • I would do it something like this. Giving invoke-command the whole array of computernames will make it run in parallel. If you return an object, you'll get the pscomputername automatically. It should give a result whether the registry entry is there or not.

    $ADSearchBaseComputers = 'ou=computers,ou=xxx,ou=xx,ou=xxx,dc=xx,dc=xxx,dc=xxx'
    $computers= get-adcomputer -filter * -searchbase $ADSearchBaseComputers |
      select -ExpandProperty Name
    Invoke-Command $computers {    
      $RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
      $RegName = Get-ItemProperty -Path $RegPath -Name MTBLogin
      [pscustomobject]@{RegName = [boolean]$RegName}
    }
    
    RegName PSComputerName RunspaceId
    ------- -------------- ----------
       True COMP001        d4124bfd-f3d1-4af0-b065-1607627f224a
       True COMP002        d4124bfd-f3d1-4af0-b065-1607627f224b
      False COMP003        d4124bfd-f3d1-4af0-b065-1607627f224c