拆分路径从服务路径名中删除“´”

时间:2019-02-25 02:22:59

标签: powershell split path scripting

这很简单,Split-Path从您从任何服务查询的每个路径名中删除最后一个'"':

$service = get-wmiobject -query 'select * from win32_service where name="SQLBrowser"';
Write-output $service.pathname 
Write-output $service.pathname | Split-Path

enter image description here

我尝试了一些服务,并且总是一样。

您认为这是我们需要向Microsoft标记的PowerShell错误吗?

有什么解决方法吗?

编辑:感谢@ mklement0的答复和解决方法。

事实证明这确实是Microsotf PowerShell bug

1 个答案:

答案 0 :(得分:2)

您的.PathName调用返回的Win32_Service实例的 Get-WmiObject属性

  • 有时包含在可执行路径周围带有嵌入双引号的值

    • 此类嵌入的双引号不是路径的一部分,必须进行进一步的处理(例如,通过Split-Path将其删除
  • 可能还包含自变量 ,以传递给可执行文件,无论该可执行文件是否被双引号。

注意:某些Win32_Service实例在其$null属性中返回.PathName

要处理这两种情况,请使用以下方法:

$service = get-wmiobject -query 'select * from win32_service where name="SQLBrowser"'

$serviceBinaryPath = if ($service.pathname -like '"*') { 
                       ($service.pathname -split '"')[1] # get path without quotes
                     } else {
                       (-split $service.pathname)[0] # get 1st token
                     }

# Assuming that $serviceBinaryPath is non-null / non-empty, 
# it's safe to apply `Split-Path` to it now.

请注意,相当多的服务使用通用的svchost.exe可执行文件,因此.PathName的值不一定反映该服务的特定二进制文件-请参见this answer

顺便说一句:Get-WmiObject在PowerShell v3中已被弃用,而推荐使用Get-CimInstance-请参见this answer

相关问题