Windows restart remote service

Windows restart remote service

July 25, 2023
Windows
Restart-Remote-Service

Windows如何方便的重启远程服务器里的服务,在不使用远程连接的情况下?

注意:服务(名称:service-name)已在远程机器上创建。

  1. 在本机新建映射网络驱动器.

  2. 打开映射好的文件夹,在其中添加batps1文件:

restart.bat:

@echo off
for %%i in (service-name) do (
    echo the service '%%i' is being starting...
    sc query %%i
    net stop %%i
    net start %%i
    sc query %%i
    echo service '%%i' started.
)
pause

restart.ps1:

$Username = 'Name'
$Password = 'Password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Invoke-Command -ComputerName [Remote-IP] -ScriptBlock { Get-Service WinRM } -credential $Cred
Invoke-Command -ComputerName [Remote-IP] -credential $Cred -ScriptBlock { E:\win-dms4\restart.bat } # 此处指定上述bat文件在远程机器上的决对路径
Read-Host -Prompt "Press Enter to exit"

完成后,只要在本机打开映射的文件夹,使用PowerShell执行restart.ps1脚本,即可快速重启指定服务。