Simplest way to restart service on a remote computer

后端 未结 11 1996
我寻月下人不归
我寻月下人不归 2020-12-23 13:07

What\'s the easiest programmatic way to restart a service on a remote Windows system? Language or method doesn\'t matter as long as it doesn\'t require human interaction.

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 13:51

    If you attempting to do this on a server on different domain you will need to a little bit more than what has been suggested by most answers so far, this is what I use to accomplish this:

    #Configuration
    $servername = "ABC",
    $serviceAccountUsername = "XYZ",
    $serviceAccountPassword = "XXX"
    
    #Establish connection
    try {
        if (-not ([System.IO.Directory]::Exists('\\' + $servername))) {
            net use \\$servername /user:$serviceAccountUsername $serviceAccountPassword
        }
    }
    catch {
        #May already exists, if so just continue
        Write-Output $_.Exception.Message
    }
    
    #Restart Service
    sc.exe \\$servername stop "ServiceNameHere"
    sc.exe \\$servername start "ServiceNameHere"
    

提交回复
热议问题