如何使用PowerShell提取所有服务的“可执行路径”

时间:2014-06-27 10:02:10

标签: powershell service powershell-v2.0 powershell-v3.0

Get-Service *sql* | sort DisplayName | out-file c:/servicelist.txt

我有一个单行PowerShell脚本来提取我本地计算机上运行的所有服务的列表,现在,除了显示“状态”,“名称”和“显示名称”之外,我还想显示“路径到可执行“

6 个答案:

答案 0 :(得分:43)

我认为您需要诉诸WMI:

Get-WmiObject win32_service | ?{$_.Name -like '*sql*'} | select Name, DisplayName, State, PathName

<强>更新 如果要对选定的数据执行某些操作,可以使用here所述的计算属性。

例如,如果您只想在路径名的引号内使用文本,则可以拆分双引号并获取数组项1:

Get-WmiObject win32_service | ?{$_.Name -like '*sql*'} | select Name, DisplayName, @{Name="Path"; Expression={$_.PathName.split('"')[1]}} | Format-List

答案 1 :(得分:4)

WMI查询的变体可能更快(我只需要为SCCM客户端执行此操作)

$SQLService=(get-wmiobject -Query 'Select * from win32_service where Name like "*SQL*"') | Select-object Name, DisplayName, State, Pathname

另一个技巧是如果你想要没有Double Quotes的路径名来捕获多个SQL结果(这样你就可以对它们采取行动)

$SQLService | Select-Object Name, DisplayName, State, @{Name='PathName';Expression=$_.Pathname.replace('"','')}

-query(或get-wmiobject)中使用get-ciminstance的最大好处是处理速度。较旧的示例获取完整列表然后过滤,而后者获取非常直接的列表。

只需加两美分:)

干杯! 肖恩 通力技术

答案 2 :(得分:1)

您还可以使用正则表达式模式并将结果转储到文件中。

Get-WmiObject win32_service | ?{$_.Name -match '^sql'} | select Name, DisplayName, State, PathName >> C:\temp\sqlservices.txt

答案 3 :(得分:1)

由于Get-WmiObject在PowerShell Core中已被弃用,因此您可以使用

Get-CimInstance -ClassName win32_service | ?{$_.Name -match '^sql'} | Select Name, DisplayName, State, PathName >> C:\temp\sqlservices.txt

相反。

答案 4 :(得分:0)

我对接受的答案使用 Expression={$_.PathName.split('"')[1]}} 感到不舒服,因为它不处理我在数据中看到的引号、空格和参数的变体。

这是一个笨重的方法。

function PathFromServicePathName($pathName) {
  # input can have quotes, spaces, and args like any of these:
  #   C:\WINDOWS\system32\lsass.exe
  #   "C:\Program Files\Realtek\Audio\HDA\RtkAudioService64.exe"
  #   C:\WINDOWS\system32\svchost.exe -k netsvcs -p
  #   "C:\Program Files\Websense\Websense Endpoint\wepsvc.exe" -k ss

  # if it starts with quote, return what's between first and second quotes
  if ($pathName.StartsWith("`"")) {
    $pathName = $pathName.Substring(1)
    $index = $pathName.IndexOf("`"")
    if ($index -gt -1) {
      return $pathName.Substring(0, $index)
    }
    else {
      # this should never happen... but whatever, return something
      return $pathName
    }
  }
  
  # else if it contains spaces, return what's before the first space
  if ($pathName.Contains(" ")) {
    $index = $pathName.IndexOf(" ")
    return $pathName.Substring(0, $index)
  }
  
  # else it's a simple path
  return $pathName
}

Get-WmiObject win32_service | select Name, DisplayName, @{Name="Path"; Expression={PathFromServicePathName $_.PathName}} | Format-List

答案 5 :(得分:0)

具有完整路径的格式列表的变体,导致文件:

Get-WmiObject win32_service | Format-Table -Wrap -AutoSize -Property State,Name,PathName | out-file C:\servicelist.txt