Use a function in Powershell replace

You can use the static Replace method from the [regex] class:

[regex]::Replace($text,'-(\d*)-',{param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})

Alternatively you can define a regex object and use the Replace method of that object:

$re = [regex]'-(\d*)-'
$re.Replace($text, {param($match) "This is the image: $(Get-Base64 $match.Groups[1].Value)"})

For better readability you could define the callback function (the scriptblock) in a separate variable and use that in the replacement:

$callback = {
  param($match)
  'This is the image: ' + (Get-Base64 $match.Groups[1].Value)
}

$re = [regex]'-(\d*)-'
$re.Replace($text, $callback)

Leave a Comment