regex - 将 $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
}
}
解决方案
推荐阅读
- azure - Oracle 数据到 Azure SQL 的近实时 ETL
- scala - 为什么可以将 Unit 分配给元组而不会出现编译错误?
- spring-boot - 如何使用 Spring Boot 在运行时配置 Micrometer 的监控系统
- linq - 我有一部分需要比较的 LINQ
- c++ - `this` 指针的值在对象的生命周期内是常量吗?
- python - 如何使用 Python 将 HTML 文件上传到 Azure Web App?
- gcc - 为什么 readelf 在 .dynsym 符号表中的 FUNC 符号名称后添加“@GLIBC_2.2.5 (2)”
- javascript - Vue:将焦点设置到动态输入框
- .net-core - Net Core Worker Windows 服务中的 EF Core DBContext
- google-cloud-platform - 使用 Bind9 在 Google Cloud Platform 中创建 DNS 转发