powershell-2.0 - 在 PowerShell v2.0 中导入和测试正在运行的服务列表
问题描述
我一直在编写一个脚本来从服务器复制正在运行的服务,然后导出该列表。重新启动服务器后,我们将列表与重新启动的服务器上运行的服务进行比较,并重新启动任何未启动的服务。问题是服务器是 2.0 版,我没有更新服务器的选项。我的代码如下所示:
# To create the list of services in text file
(Get-Service | Where-Object {$_.Status -eq "Running"}).Name |
Out-File "C:\ListOfServices.txt"
# For testing add BlackJack as a service that doesn't exist
#Restart-Computer -Force
Write-Host "Starting required services " -ForegroundColor Cyan
$date = Get-Date -Format G
Write-Host $date -ForegroundColor Cyan
# Services array needed to be started when the Server comes back up
$ServiceNameArray = Get-Content -Path "C:\ListOfServices.txt"
foreach ($serviceName in $ServiceNameArray) {
if (Get-Service $serviceName -ErrorAction SilentlyContinue) {
if ((Get-Service $serviceName).Status -eq 'Running') {
Write-Host "$serviceName found, and is running" -ForegroundColor Green
} else {
Write-Host "$serviceName found, but it is not running." -ForegroundColor Yellow
Stop-Service -InputObject $serviceName
Get-Service -InputObject $serviceName
Start-Sleep 3
Start-Service -InputObject $serviceName -ErrorAction SilentlyContinue
$services = $serviceName
$maxRepeat = 20
$status = "Stopped" # change to Stopped if you want to wait for services to start
do {
$count = (Get-Service $services | ? {$_.status -eq $status}).Count
$maxRepeat--
sleep -Milliseconds 1000
} until ($count -eq 0 -or $maxRepeat -eq 0)
Get-Service -InputObject $serviceName
}
} else {
Write-Host "$serviceName not found" -ForegroundColor Red
}
}
Write-Host "Starting required services has ended" -ForegroundColor Cyan
$date = Get-Date -Format G
Write-Host $date -ForegroundColor Cyan
Remove-Item "C:\ListOfServices.txt"
Write-Host "Removed Services text file" -ForegroundColor Green
解决方案
推荐阅读
- xcode - 测试使用 Google FileStream 保存的 Xcode 项目
- javascript - Jest mockRejectedValue 在节点中抛出未处理的承诺拒绝
- sql - 如何逐字反转列中的字符串?
- c# - 从我的应用程序中拖动项目时,我可以限制仅拖动到 Windows 资源管理器中并在完成后获取目标路径吗?
- javascript - 如何通过 ajax 调用使用 php 将变量或查询传递给 python 脚本?
- python - 如何访问 POST 请求中的嵌入键值
- azure - Azure 门户上的共享或私有资源
- r - 从平均 GLM 模型绘制预测:eval 中的错误(predvars,data,env):找不到对象“x3”
- java - 防止使用 nio 删除锁定文件
- javascript - 如何使用 HTML 中的滑块更改表格单元格中的值