并行处于多个远程服务器上的Windows服务操作

时间:2013-11-09 07:49:24

标签: powershell powershell-remoting powershell-v1.0

我在同一个网络上有3台服务器并且具有相同的用户名和密码才能登录,我想在其中执行以下操作:

*Check if Service1 is running or not
*If it is running, stop the service 
*Set Service1 to disable mode 
*If it is not running, do nothing
*Check if Service2 is running 
*If it is running, stop the service 
*Set Service2 to disable mode 
*If it is not running, do nothing

依此类推Service3,.. 4,.. 5 ...

我想在第一台服务器上创建一个Master.bat文件,它应该在所有3台服务器上并行执行上述操作。

我正在尝试下面但没有得到我如何在相同的代码中为多于1个服务做这个以及它有点冗长。有没有其他简短方法在批处理或PowerShell中执行此操作?

original_serverlist.txt:

Server1
Server2
Server3

代码:

copy original_serverlist.txt serverlist.txt

:repeat
set currentserver=
for /f "eol=; tokens=1*" %%i in (serverlist.txt) do set currentserver=%%i
if "%currentserver%"=="" goto end

for /F "tokens=3 delims=: " %%H in ('SC query Service1 ^| findstr "        STATE"') do (
  if /I "%%H" "RUNNING" (
  net stop Service1
  echo Service1 stopped @ %date% %time% > C:\result.txt 
  sc config Service1 start= disabled
  echo Service1 set disabled @ %date% %time% >> C:\result.txt 
  )
)

type serverlist.txt| find /v "%currentserver%"> serverlist1.txt
copy serverlist1.txt serverlist.txt
goto repeat

:end
del serverlist.txt
del serverlist1.txt

EDIT1

我在PS中并不像批处理那样舒服,但我想学习这些东西,所以在这里把我的确切要求学习如何在PowerShell中用代码说明来实现它。

我需要在Server1上具有 Master.ps1 的所有三个远程服务器(Server1,Server2,Server3)上执行以下相同的操作集:

run command  cmd /c iisreset/stop and set IIS service to Disabled mode
Stop service1 and set it to Disabled mode
Stop service2 and set it to Disabled mode
Stop service3 and set it to Disabled mode
Kill process jusched.exe
Kill process conhost.exe

1 个答案:

答案 0 :(得分:3)

在powershell 3.0中

$services = "service1", "service2", "service3"
"server1", "server2", "server3" | % {
        Get-Service -Computer $_ $services | ? State -eq "Running" | Stop-Service -Force -PassThru | Set-Service -StartupType Disabled
}

如果您当前的域用户没有足够的权限,则需要启用powreshell远程处理才能使此工作正常,并在-Credential参数的任何位置添加-Computer选项。

更通用的选项是使用哈希

$ServiceMap = @{ "server1": ("service11", "service12");
                 "server2": ("service21" ... ) }

您还需要检查错误..

要实现并行执行,您可以执行以下操作:

workflow set_services {
  param(
    [string[]]$Computers, [string[]]$Services
  )

  foreach -parallel ($computer in $computers) {
    Get-Service -ComputerName $computer $services | ? State -eq "Running" | Stop-Service -Force -PassThru | Set-Service -StartupType Disabled 
  }    
}

顺便说一下,不要再在任何地方使用批处理脚本了。