【问题标题】:How to pull physical path of a Windows Service using Get-Service command如何使用 Get-Service 命令拉取 Windows 服务的物理路径
【发布时间】:2012-09-16 23:34:58
【问题描述】:

我需要在 Win 2k8 上运行的一组服务器上提取所有 Windows 服务的物理执行路径。由于此操作系统附带的 powershell 版本是 2.0,我想使用 Get-service 命令而不是 Get-WmiObject。 我知道我可以使用下面给出的命令拉出物理路径

$QueryApp = "Select * from Win32_Service Where Name='AxInstSV'"
$Path = (Get-WmiObject -ComputerName MyServer -Query $QueryApp).PathName

我不希望这个命令拉物理路径,但想使用 PS 版本 2.0 附带的 Get-Service 命令。

任何帮助将不胜感激。

【问题讨论】:

    标签: windows powershell windows-services powershell-2.0


    【解决方案1】:

    即使使用 PowerShell 3,我也看不到通过 Get-Service 获取它的方法。

    这个 1-liner 将为您提供路径名,尽管会少一些首选的“向左过滤”行为:

    gwmi win32_service|?{$_.name -eq "AxInstSV"}|select pathname
    

    或者,如果你只想要字符串本身:

    (gwmi win32_service|?{$_.name -eq "AxInstSV"}).pathname
    

    【讨论】:

    • 那个 .NET 代码正在做这个 PowerShell 代码正在做的事情,只是更冗长。
    【解决方案2】:

    我想做类似的事情,但是基于搜索/匹配服务下运行的进程的路径,所以我使用了经典的 WMI Query 语法,然后通过 format-table 传递结果:

    $pathWildSearch = "orton";
    gwmi -Query "select * from win32_service where pathname like '%$pathWildSearch%' and state='Running'" | Format-Table -Property Name, State, PathName -AutoSize -Wrap
    

    欢迎您通过跳过定义和传递 $pathWildSearch 将其转换为单行语句,或者您可以在分号后将 gwmi 语句倒退到继续。

    【讨论】:

      【解决方案3】:

      @alroc 做得很好,但没有理由过滤所有服务。查询 WMI 就像查询一个 DB,你可以让 WMI 为你做过滤:

      (Get-CimInstance Win32_Service -Filter 'Name = "AxInstSV"').PathName
      

      探索可用于该服务的所有元数据:

      Get-CimInstance Win32_Service -Filter 'Name = "AxInstSV"' | Select-Object *
      

      【讨论】:

        【解决方案4】:

        也许不那么冗长,

        wmic service where "name='AxInstSV'" get PathName
        

        这也应该在命令提示符下工作,而不仅仅是 powershell。


        否则,如果您有进程名称本身,您可以这样做:

        wmic process where "name='AxInstSV.exe'" get ExecutablePath
        

        要读取进程路径,您需要获得许可,所以大多数情况下我对服务名称的运气更好。

        【讨论】:

          【解决方案5】:

          我无法通过 Get-Service 命令执行此操作,但如果您的服务作为自己的进程运行,那么您可以通过以下代码使用 Get-Process 命令:

          (Get-Process -Name AxInstSV).path
          

          来源: https://blogs.technet.microsoft.com/heyscriptingguy/2014/09/15/powertip-use-powershell-to-find-path-for-processes/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-09-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多