How to Restart Services on Remote Server in Powershell

I am trying to do something very simple but have lost my way. I have this script that works almost perfect. It goes into a list of servers checks for 2 services and checks if they are running. Then, it generates a list of servers that are running or stopped. Now, what I need it to do is to restart the service when it finds that it is stopped...

$Computers = Get-Content -path C:\computers.txt
$Computerobject = $null
FOREACH ( $Computer IN $Computers )
{
    TRY
    {
        $Services = $null
        $Services = (Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer -ErrorAction Stop | Select-Object Status, Name, DisplayName )
        Add-Member -InputObject $Services -NotePropertyName ComputerName -NotePropertyValue $Computer
        $ComputerProperties = [ordered] @{ComputerName=$Services.ComputerName; ServiceName=$Services.Name; Status=$Services.Status}
        $Computerobject = New-Object PSObject -Property $ComputerProperties
        $Computerobject
    }
        CATCH
        {
            Write-Host "Both services are not installed on $Computer." -ForegroundColor Red
        }
}
4

1 Answer

Following from my comment.

Like this:

$Computers = Get-Content -path C:\computers.txt
$Computerobject = $null
FOREACH ( $Computer IN $Computers )
{
    TRY
    {
        $Services = $null
        $Services = (Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer -ErrorAction Stop | Select-Object Status, Name, DisplayName )
            if($Services.Status -eq "Stopped"){ Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer | Start-Service}
        Add-Member -InputObject $Services -NotePropertyName ComputerName -NotePropertyValue $Computer
        $ComputerProperties = [ordered] @{ComputerName=$Services.ComputerName; ServiceName=$Services.Name; Status=$Services.Status}
        $Computerobject = New-Object PSObject -Property $ComputerProperties
        $Computerobject
    }
        CATCH
        {
            Write-Host "Both services are not installed on $Computer." -ForegroundColor Red
        }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest