首页 > 解决方案 > 将 $matches 转换为 PSCustomObject

问题描述

我创建了这个函数来尝试将字符串分解为可以制成 PowerShell 对象的标记组。这就是我到目前为止所拥有的。如果我在函数之外使用代码,我会得到想要的结果,但如果我尝试在函数中使用它,我什么也得不到。我相信输出正在消失。我知道我没有使用正确的术语来描述正在发生的事情。任何援助将不胜感激。

Function Convert-MatchToPSCustomObject
{
  <#
  .SYNOPSIS
    Converts $matches to PSCustomObject

  .DESCRIPTION
    Takes an input string and converts it to PSCustomObject

  .PARAMETER Pattern
      Mandatory. Pattern which to match within the string

  .PARAMETER String
      Mandatory. Input String

  .EXAMPLE
    Convert-MatchToPSCustomObject -Pattern '(?<descriptor>^\b[A-Z]{2})(?>[=])(?<value>[\w \.\-]+\b$)' -String 'CN=Only Da Best'

  .LINK
    https://regex101.com/r/1hYb2J/1/

  .LINK
    https://vexx32.github.io/2018/11/08/Named-Regex-Matches-PSCustomObject/

  .NOTES
    Version: 1.0
    Author: Kino Mondesir
  #>
  [cmdletbinding()]
  param
  (
    [Parameter(HelpMessage="Pattern to match", Position=0, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNullorEmpty()]
    [string]$pattern = '(?<descriptor>^\b[A-Z]{2})(?>[=])(?<value>[\w \.\-]+\b$)',

    [Parameter(HelpMessage="Input string", Position=1, Mandatory=$true, ValueFromPipeline=$true)]
    [ValidateNotNullorEmpty()]
    [string]$string
  )
  Try
  {
    return $string -split ',' | ForEach-Object {
      if ($PSItem -match $pattern)
      {
        $Matches.Remove(0)
        [PSCustomObject]$Matches
      }
      else
      {
        Throw "No matching items found!"
      }
    }
  } 
  Catch
  {
    $exception = $_.Exception
    Write-Error $exception.Message
    return -1
  }
}

标签: regexpowershell

解决方案


推荐阅读