分割字符串中程序与参数


先前的技巧中我们说明了如何从一行命令行中得到程序名和剔除全部的参数。今天,我们要使用一个两全其美函数,它能自定义对象返回程序名和它的参数:

function Get-Argument
{
  param
  (
    $CommandLine
  )
  
  $result = 1 | Select-Object -Property Command, Argument

  if ($CommandLine.StartsWith('"')) 
  { 
    $index = $CommandLine.IndexOf('"', 1)
    if ($index -gt 0)
    {
      $result.Command = $CommandLine.SubString(0, $index).Trim('"')
      $result.Argument = $CommandLine.SubString($index+1).Trim()
      $result
    }
  }
  else
  {
    $index = $CommandLine.IndexOf(' ')
    if ($index -gt 0)
    {
      $result.Command = $CommandLine.SubString(0, $index)
      $result.Argument = $CommandLine.SubString($index+1).Trim()
      $result
    }
  }
}



Get-Argument -CommandLine 'notepad c:\test'
Get-Argument -CommandLine '"notepad.exe" c:\test'

结果:

1

 

 

 

 

这里有个实际当中的例子,要得到全部的运行进程的名字和参数:

Get-WmiObject -Class Win32_Process |
  Where-Object { $_.CommandLine } |
  ForEach-Object {
    Get-Argument -CommandLine $_.CommandLine
  }  

结果会看起来像这个样子:

2

现在我们分开了参数和程序,你也可以尝试下分组:

Get-WmiObject -Class Win32_Process |
  Where-Object { $_.CommandLine } |
  ForEach-Object {
    Get-Argument -CommandLine $_.CommandLine
  } |
  Group-Object -Property Command |
  Sort-Object -Property Count -Descending |
  Out-GridView

原文地址:Getting Arguments from Command Line

本文链接: https://www.pstips.net/getting-arguments-from-command-line.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注