Search code examples
powershellserviceregistryevent-viewer

Powershell script gets error saying remote registry service is not turned on when it is


I have a powershell script that searches the miner logs in the applications and services folder in the event viewer and returns all logs classified as error for the ArcMap application. The script searches for every machine in our company's network. The script works when it searches on a single machine, however it returns an error saying it cannot find the RemoteRegistry service when the script searches on multiple machines. Below is the script I have so far.

$computers = Get-Content "computerlist.txt"
$logFile = "MinerErrorLogs.txt"

foreach ($computer in $computers) {
    Get-Service -ComputerName $computers -Name "RemoteRegistry" | Set-Service -StartupType Manual        -PassThru| Start-Service 
    Write-Host "Processing computer $computer..."
    $events = Get-WinEvent -ComputerName $computer -FilterHashtable @{LogName='Application'; ProviderName='ArcMap'; Level=2}
    $events | Out-File -FilePath "$env:TEMP\$logFile" -Append
}

Get-Service -ComputerName $computers -Name "RemoteRegistry" | Set-Service -Status Stopped

I have made sure the Get-Service command is included in the loop and that it stops the service when finished. Not sure why it says it cannot find it when the script tell the service to start.

Tried the "Get-Service command, put it in the loop so it turns on for every machine searched. Expected the "cannot find service" error to disappear, but it is still there.


Solution

  • A Second approach would be to use pssession to run the code from the inside:

    foreach ($client in $file){
       $Session=New-PSSession -ComputerName $client -errorAction SilentlyContinue
       if($Session){
          Write-Host "Processing computer $computer..."
          $rslt=Invoke-Command -Session $Session -ScriptBlock {
            #$remoteRegService = Get-Service -Name "RemoteRegistry"                   
            #$remoteRegService | Set-Service -StartupType Manual  -PassThru | Start-Service 
            Get-WinEvent -ComputerName $computer -FilterHashtable @{LogName='Application'; ProviderName='ArcMap'; Level=2} $events | Out-File -FilePath "$env:TEMP\$logFile" -Append                                               
            #$remoteRegService | Set-Service -Status Stopped                         
          } 
         $rslt | Out-File -FilePath "$env:TEMP\$logFile" -Append                                                                        
         Remove-pssession $Session
       }                                                                            
    }
    

    I have left the command on RemoteRegistry in the code block but commented them out, since it is possible to use them to start / stop the service but in this case from within the client there is no obvious reason to use the service.