stop or start a service on remote machine

前端 未结 3 1136
自闭症患者
自闭症患者 2021-01-16 16:36

I created a script that will start or stop a service based on it\'s display name. My script works on the local machine but I would like to make sure that it can be done on a

3条回答
  •  滥情空心
    2021-01-16 17:09

    You can't use Start-Service/Stop-Service for a remote computer, you can however pass a service object from Get-Service (using the ComputerName parameter) to Set-Service which can perform the same start/stop actions for a remote computer:

    Get-Service $ServiceName -ComputerName $ComputerName | Set-Service -Status Running
    

    I find this to be much easier than using PowerShell Remoting or WMI commands.

    You can easily update your code with minimal code changes:

    $serviceName = Read-Host -Prompt 'Please enter service name: '
    
    #get computername or use localhost for local computer
    if(($ComputerName = Read-Host 'Enter Computer Name, leave blank for local computer') -eq ''){$ComputerName = 'localhost'}
    
    $Service = Get-Service -DisplayName $serviceName -ComputerName $ComputerName -ErrorAction SilentlyContinue
    
    # Check that service name exists
    if ($Service) {
        # Check that service name is not empty
        if([string]::IsNullOrEmpty($serviceName)){Write-Host 'Service name is NULL or EMPTY'}
        else {    
            $Choice =  Read-Host -Prompt 'Would you like to start or stop the service'
    
            #Start service
            If ($Choice -eq 'start') {
                $Service | Set-Service -Status Running
                Write-Host $serviceName 'Starting...' -ForegroundColor Green
            }
    
            #Stop service
            If ($Choice -eq 'stop') {
              $Service | Set-Service -Status Stopped
              Write-Host $serviceName 'Stopping...' -ForegroundColor Green
            }
        }
    }
    else {            
        Write-Host 'Service name does not exist'            
    }
    

提交回复
热议问题