这似乎应该是非常简单的事情,但到目前为止,我无法找到方法。
我有以下脚本:
$processName = "notepad.exe"
$filter = "name like '%"+$processName+"'"
$result = Get-WmiObject win32_process -Filter $filter
$counter=1
foreach($process in $result )
{
$desc = $process.Description
$commArr = $process.CommandLine -split"( )"
$comm = $commArr[0]
$inst = $commArr[2]
write-host "$counter) -APPLICATION: $desc `r`n -LOCATION: $comm `r`n -INSTANCE: $inst"
$counter++
}
}
它告诉我有多少个给定应用程序(在本例中为notepad.exe)的实例正在运行。它返回:
Application: "notepad.exe"
LOCATION: "C:\Windows\system32\notepad.exe"
Instance: " "
但是对于位置我只需要第一部分"C:\Windows\system32"
我尝试了split-path
:
$commShort = split-path($comm)
但我收到错误:
Split-Path : Cannot find drive. A drive with the name '"C' does not exist.
如果我通过手动添加位置来尝试这个,它可以正常工作:
$commShort = split-path("C:\Windows\system32\notepad.exe")
这有什么诀窍吗?
答案 0 :(得分:1)
您需要替换
$commArr = $process.CommandLine -split"( )"
$comm = $commArr[0]
$inst = $commArr[2]
在你的for循环中
$commArr = $process.CommandLine.Split()
$comm = Split-Path $commArr[0]
$inst = $commArr[1]
完整代码:
$processName = "notepad.exe"
$filter = "name like '%"+$processName+"'"
$result = Get-WmiObject win32_process -Filter $filter
$counter=1
foreach($process in $result )
{
$desc = $process.Description
$commArr = $process.CommandLine.Split()
$comm = Split-Path $commArr[0]
$inst = $commArr[1]
write-host "$counter) -APPLICATION: $desc `r`n -LOCATION: $comm `r`n -INSTANCE: $inst"
$counter++
}
您也可以使用Write-Host (Split-Path $process.Path)
让C:\Windows\system32
进入你的圈内。
答案 1 :(得分:0)
要获取路径的父文件夹,请使用
Split-Path -Parent $thePath
switch参数-parent
告诉PowerShell只返回最后一部分剪切的路径(但处理根路径)。