
cd "C:\Program Files\Tenable\Nessus Agent" 
$nessusstatus = .\nessuscli.exe agent status

$ServiceName = "Tenable Nessus Agent"
Write-Host "Stopping Nessus Agent" 
Stop-Service $ServiceName
Start-Sleep -Seconds 5
$service = (Get-Service -Name $ServiceName -ErrorAction Stop)

if ($service.Status -eq "Stopped") { 

    if ($nessusstatus[2].Contains("disconnected")) {     
        .\Nessuscli.exe plugins --reset 
        start-Service $ServiceName
        Start-Sleep -Seconds 600
        $pluginstatus = (.\Nessuscli.exe plugins --info) | Out-String
        $nessusstatus = .\nessuscli.exe agent status
        Write-Host "Plugin Reset and Agent Started: "$nessusstatus[2]
  
        return true
    }
    elseif ($nessusstatus[2].Contains("authentication error")) {     
        .\nessuscli.exe agent link --key=0f0147f977db9a4ea74c34b2a24221cdac7715a36665525537718f48e5edafd5 --host=paptennm001.ccx.carecentrix.com --port=8834 --groups="Agent - Windows Servers"
        .\Nessuscli.exe plugins --reset 
        Start-Sleep -Seconds 600
        $nessusstatus = .\nessuscli.exe agent status
        Write-Host "Agent Re-Linked: "$nessusstatus[2]
        Start-Service $ServiceName 
        return true 
    }
    elseif ($nessusstatus[2].Contains("Not linked to a manager")) {     
        .\nessuscli.exe agent link --key=0f0147f977db9a4ea74c34b2a24221cdac7715a36665525537718f48e5edafd5 --host=paptennm001.ccx.carecentrix.com --port=8834 --groups="Agent - Windows Servers"
        Start-Service $ServiceName 
        Start-Sleep -Seconds 600
        $nessusstatus = .\nessuscli.exe agent status
        Write-Host "Agent Re-Linked: "$nessusstatus[2]
        return true 
    }
    elseif ($nessusstatus[2].Contains("Connected to paptennm001.ccx.carecentrix.com:8834")) {     
        Write-Host "Nessus Agent is connected and healthy: "$nessusstatus[2]
        Start-Service $ServiceName 
        return true
    }
    else {
        Write-Host "Unknown Remediation Required: "$nessusstatus[2]
        Start-Service $ServiceName 
        return false
    }

}
else { 
    Write-Host "Nessus Agent Not Stopped"
    return false
}
