2014-10-01 63 views
0

這看起來應該是非常簡單的事情,但到目前爲止我找不到這樣做的方式。Powershell v2 - 將Process.Commandline拆分成零件

我有以下腳本:

$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")

是否有一些技巧呢?

回答

1

您需要

$commArr = $process.CommandLine.Split() 
$comm = Split-Path $commArr[0] 
$inst = $commArr[1] 

更換

$commArr = $process.CommandLine -split"()" 
$comm = $commArr[0] 
$inst = $commArr[2] 

for循環的完整代碼:

$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你內心for循環。

+0

乾杯,第一部分不幸失敗,原因與原來相同。然而第二部分('Split-Path $ process.Path')是一種享受。 – IGGt 2015-07-14 07:21:41

+0

我正在運行Powershell v4。我在Windows 7 32位上使用Powershell ISE運行代碼。你使用的是什麼版本的Windows&Powershell? – Ishan 2015-07-15 22:54:09

+0

那可能會解釋一下。 Windows 7 64bit和Powershell v2(我們有一些較舊的服務器) – IGGt 2015-07-16 07:43:31

0

爲了得到一個路徑的父文件夾使用

Split-Path -Parent $thePath 

開關參數-parent告訴PowerShell來只是最後一部分切返回路徑(但處理根路徑)。

+0

歡呼,但不幸的是它不工作。如果我輸入$ commShort = split-path -parent $ comm,我仍然得到錯誤。 (手動添加進程,例如$ comm =「C:\ Windows \ system32 \ notepad.exe」) – IGGt 2014-10-01 15:12:20

+0

@IGGt我懷疑你的'$ comm'沒有你期望的值。 ('Write-Debug'和'$ DebugPreference'或者(對於高級函數)'-Debug'是非常有用的。) – Richard 2014-10-01 15:36:56

+0

歡呼聲,這對我們很有幫助。不幸的是,在這種情況下它不是問題:'DEBUG:「C:\ Windows \ system32 \ notepad.exe」' – IGGt 2014-10-01 15:53:04