Powershell显示所有已停止的自动服务并尝试启动这些服务
我想创建一个PS脚本,它将显示所有已停止的自动服务,并在之后尝试启动这些服务 下面是PS代码。它将成功显示远程服务器上所有已停止的服务Powershell显示所有已停止的自动服务并尝试启动这些服务,powershell,Powershell,我想创建一个PS脚本,它将显示所有已停止的自动服务,并在之后尝试启动这些服务 下面是PS代码。它将成功显示远程服务器上所有已停止的服务 Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |` where {($_.startmode -like "*auto*") -and ` ($_.state -notlike "*running*") -and `
Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
where {($_.startmode -like "*auto*") -and `
($_.state -notlike "*running*") -and `
($_.name -notlike "gupdate") -and `
($_.name -notlike "remoteregistry") -and `
($_.name -notlike "sppsvc") -and `
($_.name -notlike "lltdsvc") -and `
($_.name -notlike "KDService") -and `
($_.name -notlike "wuauserv")
}|`
select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize
您只需将查询结果存储到一个变量中,而无需选择和显示它,就可以得到一组
win32\u服务
实例,它们都有一个StartService()
方法。通常,最好检查您正在使用的wmi类的文档,其中大多数都有作用于所表示对象的方法,而不必通过管道将它们传递给其他cmdlet,如大多数Powershell对象:
您可以这样使用它:
$services = Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
where {($_.startmode -like "*auto*") -and `
# [...]
}
$service | select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize
$Service | ForEach {$_.StartService()}
也可以考虑使用Get服务,除非您需要使用WMI。你有一些不同,但想法是一样的:
$Services = Get-Service -ComputerName SERVER1,SERVER2 |`
where {($_.StartType -eq "Automatic") -and `
($_.Status -notlike "*running*") -and `
($_.Name -notlike "gupdate") -and `
# ...
}
$Services | select Description,Name,StartType,Status,MachineName |ft -AutoSize
$Services | Start-Service
此外,您还可以通过使用-notin
操作符大大简化过滤器:
where {($_.startmode -like "*auto*") -and `
($_.state -notlike "*running*") -and `
($_.name -notin "gupdate","remoteregistry","sppsvc","lltdsvc","KDService","wuauserv")
}
然后,您只需将结果通过管道传输到
{$\u.StartService()}
。如果你想解释显示结果,需要更多的爱。考虑使用WMI代替WMI。