使用/ PowerShell获取Windows Server上所有已停止自动服务的属性

时间:2014-06-27 03:33:40

标签: powershell windows-services windows-server-2008 windows-server-2012 windows-server-2012-r2

我想获取Windows服务器上处于“已停止”状态的所有自动服务的显示名称,名称,启动模式,开始名称和状态。通常,我会做

get-wmiobject -class win32_service | ? {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"} | select DisplayName, Name, StartMode, StartName, State

但是,上面的cmdlet没有区分"自动"和#34;自动延迟启动"。我下面的cmdlet不会报告任何具有自动延迟启动状态的服务,但我不知道如何让它也显示我需要的其他属性。

(Get-WmiObject -Class Win32_Service -Filter "state = 'stopped' and startmode = 'auto'" | Select-Object -ExpandProperty name) | Where-Object {(Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Services | Where-Object {$_.property -contains "DelayedAutoStart"} | Select-Object -ExpandProperty PSChildName) -notcontains $_} | Select-Object @{l='Service Name';e={$_}}

如何修改上面的cmdlet,以便它还显示我想要的其他属性?

修改 我知道下面的方法可行,但效率低且非类似PowerShell。

$auto_services = @((get-wmiobject -class win32_service -filter "state='stopped' and startmode='auto'" | select-object -expandproperty name) | ? {(get-childitem HKLM:\SYSTEM\CurrentControlSet\Services | ? {$_.property -contains "DelayedAutoStart"} | Select-Object -ExpandProperty PSChildName) -notcontains $_})

foreach ($service in $auto_services) { Get-WMIobject -class win32_service | ? {$_.Name -eq $service} | Select DisplayName, name, startmode, startname, state}

编辑2: 更好的是,如果你能列出所有服务和所需的属性,并以某种方式使它成为"自动延迟启动"服务实际显示"自动延迟启动"作为StartMode,而不是只显示" Auto"。

1 个答案:

答案 0 :(得分:2)

使用PowerShell 4.0(使用-PipelineVariable),您可以执行以下操作:

get-wmiobject -class win32_service  -PipelineVariable s | ? {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"}| where {(Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\services\$($_.name)" -Name 'DelayedAutoStart' -ErrorAction  "silentlycontinue").DelayedAutoStart -eq 1} | % {select  -InputObject $s -Property DisplayName, Name, StartMode, StartName, State}

使用以前的版本,您应该在管道中将服务对象分配给var。

 get-wmiobject -class win32_service  | % {$s=$_;$s} | ? {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"}| where {(Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\services\$($_.name)" -Name 'DelayedAutoStart' -ErrorAction  "silentlycontinue").DelayedAutoStart -eq 1} | % {select  -InputObject $s -Property DisplayName, Name, StartMode, StartName, State}

被修改

以下是“自动”启动模式中所有停止服务的PowerShell 2.0版本,而不是“自动延迟启动”:

get-wmiobject -class win32_service  | % {$s=$_;$s} | ? {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"}| % {$d = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\services\$($_.name)" -Name 'DelayedAutoStart' -ErrorAction  "silentlycontinue").DelayedAutoStart;$_ } | where {$d -ne '1'} |% {select  -InputObject $s -Property @{name="DelayedAutoStart";expression={$d}},DisplayName, Name, StartMode, StartName, State}