正则表达式接受命令并分割命令、参数和参数值

Nic*_* W. 2 string powershell parsing command-line-arguments

下午好,

我认为我在这项特殊任务中有点超出了我的能力范围。我正在尝试创建一个正则表达式匹配函数来输入命令,并拆分命令名称、参数和参数值。

新变量 -Name Something -Force 结果应该是

  1. 新变量
  2. -姓名
  3. 某物
  4. -力量

到目前为止我已经想出了这个,但它只捕获了第一个参数集。

额外奖励:有什么方法可以使命令后的所有匹配项以增量方式命名吗?比如说参数 1、值 1、参数 2、值 2 等等?

^(?P<Command>[a-zA-Z]+-[a-zA-Z]+)(?: +)((-\S+)(?: |:|=)(.*){0,1})(?: +)
Run Code Online (Sandbox Code Playgroud)

我根本不知道 PowerShell 解析器的存在,但这太棒了。这是我确定的代码。谢谢你们的帮助!

#Split up the command argument, needed to pull useful information from the command.
New-Variable -force -Name SplitCommand -Value ([System.array]$Null)
$null = [System.Management.Automation.Language.Parser]::ParseInput($Command, [ref]$SplitCommand,[ref]$Null)
$SplitCommand = $SplitCommand.where({-NOT [String]::IsNullOrEmpty($_.text)}).text
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

不要为此使用正则表达式 - 请改用内置解析器:

# Prepare command to parse
$command = 'New-Variable -Name Something -Force'

# Parse command invocation - Parser will return an Abstract Syntax Tree object
$parserErrors = @()
$AST = [System.Management.Automation.Language.Parser]::ParseInput($command, [ref]$null, [ref]$parserErrors)

if($parserErrors){
    # error encountered while parsing script
}
else {
    # No errors, let's search the AST for the first command invocation
    $CommandInvocation = $AST.Find({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $false)

    # Get the string representation of each syntax element in the command invocation
    $elements = $CommandInvocation.CommandElements |ForEach-Object ToString
}
Run Code Online (Sandbox Code Playgroud)

通过您的输入 ( New-Variable -Name Something -Force),将生成以下字符串:

PS ~> $elements
New-Variable
-Name
Something
-Force
Run Code Online (Sandbox Code Playgroud)

注意:与参数紧密绑定的参数:将被解释为单个联合语法元素,例如。'Get-Thing -Name:nameOfThing' 将仅生成两个字符串 (Get-Thing-Name:nameOfThing) - 如果您希望将它们拆分为单独的字符串,请在将它们转换为字符串之前考虑到这一点:

$elements = $CommandInvocation.CommandElements |ForEach-Object {
  if($null -ne $_.Argument){
    # tightly bound argument, output both separately
    "-$($_.ParameterName)"
    $_.Argument
  } else {
    # just the parameter name, output as-is
    $_
  }
} |ForEach-Object ToString
Run Code Online (Sandbox Code Playgroud)