简体   繁体   English

Powershell 脚本检查多台远程机器上的服务并在它们未运行时启动它们

[英]Powershell script to checking services on multiple remote machines and to start them if they are not running

New to Powershell, My goal is to go through a list of remote Computers and check to see if certain services are running on them and starting the services if they are not. Powershell 的新手,我的目标是通过远程计算机列表访问 go,并检查某些服务是否在它们上运行,如果没有则启动服务。 what would be the best approach in creating a variable for the services on said servers?为所述服务器上的服务创建变量的最佳方法是什么?

Server1.txt - 'ServiceA ServiceB ServiceC'
Server2.txt - 'ServiceD ServiceE ServiceF'
Server3.txt - 'ServiceG ServiceH'

$services = get-content .\Server1.txt

       

$services | ForEach {
    try {
        Write-Host "Attempting to start '$($.DisplayName)'"
        Start-Service -Name $.Name -ErrorAction STOP
        Write-Host "SUCCESS: '$($.DisplayName)' has been started"
    } catch {
        Write-output "FAILED to start $($.DisplayName)"
    }
}

Thank you.谢谢你。

In your input, you have mentioned one text file for each server which is not advisable.在您的输入中,您提到了每个服务器的一个文本文件,这是不可取的。 Also there is no computer name in your Start-service Command.您的 Start-service 命令中也没有计算机名称。 Please find my input sample below.请在下面找到我的输入示例。

server1-serviceA,ServiceB,ServiceC
server2-serviceD,ServiceE,ServiceF
server3-serviceG,ServiceH,ServiceI

And here is the powershell script, since you have mentioned different services for each server there is a need for using split function.这是 powershell 脚本,因为您已经提到每个服务器的不同服务,所以需要使用拆分 function。

$textFile = Get-Content C:\temp\servers.txt

foreach ($line in $textFile) {

    $computerName = $line.split("-")[0]  #Getting computername by using Split
    $serviceNames = $line.split("-")[1]  #Getting Service names by using split

    foreach ($serviceName in $serviceNames.split(",")) {
        # Again using split to handle multiple service names

        try {
            Write-Host " Trying to start $serviceName in $computerName"
            Get-Service -ComputerName $computerName -Name $serviceName | Start-Service -ErrorAction Stop
            Write-Host "SUCCESS: $serviceName has been started"
        }
        catch {
            Write-Host "Failed to start $serviceName in $computerName"
        }
     
    }
}

I haven't tested the script for starting the service, but the loop works properly for multiple servers and their respective services.我没有测试启动服务的脚本,但循环适用于多个服务器及其各自的服务。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM