I'm having some difficulty finding a "native" powershell -replace call that would replace a match with something based on the match. E.g. in perl it would be like this:
my %definedVars = ( ab => "hello", cd => "there" );
my $str = q"$(ab) $(cd)";
$str =~ s/\$\(([^)]+)\)/$definedVars{$1}/ge;
print "$str\n";
I was thinking that in powershell, it'd be something like this:
$definedVars = @{ ab = 'hello'; cd = 'there' }
'$(ab) $(cd)' -replace "\$\(([^)]+)\)", { $definedVars[$1] }
I've looked around and I think that the -replace
switch doesn't have an deferred evaluator, so I'd have to use the .NET replace
function, but I'm not entirely sure how that works. I'm thinking it would be something like this:
$definedVars = @{ ab = 'hello'; cd = 'there' }
[regex]::replace('$(ab) $(cd)',
"\$\(([^)]+)\)",
{ $definedVars[$_.Groups[1].Value] } )
Documentation is sparse, so if you could also state where you got your info from, that would be great.