【发布时间】:2021-06-10 00:20:24
【问题描述】:
我正在尝试做一些非常简单的事情,但却迷失了方向。我有这个几乎完美的脚本。它进入服务器列表检查 2 个服务并检查它们是否正在运行。然后,它会生成一个正在运行或停止的服务器列表。现在,我需要它做的是在发现服务停止时重新启动服务......
$Computers = Get-Content -path C:\computers.txt
$Computerobject = $null
FOREACH ( $Computer IN $Computers )
{
TRY
{
$Services = $null
$Services = (Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer -ErrorAction Stop | Select-Object Status, Name, DisplayName )
Add-Member -InputObject $Services -NotePropertyName ComputerName -NotePropertyValue $Computer
$ComputerProperties = [ordered] @{ComputerName=$Services.ComputerName; ServiceName=$Services.Name; Status=$Services.Status}
$Computerobject = New-Object PSObject -Property $ComputerProperties
$Computerobject
}
CATCH
{
Write-Host "Both services are not installed on $Computer." -ForegroundColor Red
}
}
【问题讨论】:
-
如果您想启动该服务,请将其发送至
Start-Service。或者只是简单地使用相同的 cmdlet 启动它 -
在你的第二个
$Services变量之后添加这个:if($Services.Status -eq "Stopped"){ Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer -ErrorAction Stop | Start-Service} -
$Services = $null $Services = if($Services.Status -eq "Stopped"){ Get-Service -Name 'CrystalToPDF','Bradware - BoxUploadService' -computername $Computer -ErrorAction Stop |开始服务| Select-Object Status, Name, DisplayName } Add-Member -InputObject $Services -NotePropertyName ComputerName -NotePropertyValue $Computer $ComputerProperties = [ordered] @{ComputerName=$Services.ComputerName;服务名=$Services.Name; Status=$Services.Status} $Computerobject = 新对象 PSObject -Property $ComputerProperties $Computerobject
-
我添加并运行了它,但出现了一堆错误。
标签: powershell