1

In PowerShell 3 I'm performing a regex replace on a string and I would like to pass the '$1' positional parameter to a function as a variable (see the last line in script.ps1)

My code

testFile.html

<%%head.html%%>
<body></body></html>

head.html

<!DOCTYPE html>
<html><head><title></title></head>

script.ps1

$r = [regex]"<\%\%([\w.-_]+)\%\%>" # matches my markup e.g. <%%head.html%%>
$fileContent = Get-Content "testFile.html" | Out-String # test file in which the markup should be replaced
function incl ($fileName) {        
    Get-Content $fileName | Out-String
}
$r.Replace($fileContent, (incl '$1'));

The problem is on the last line in script.ps1 which is that I couldn't find a way how to resolve the function call so that Get-Content gets the correct value from $fileName. It sees it as '$1' reading from the error message:

Get-Content : Cannot find path 'C:\path\to\my\dir\$1' because it does not exist.

I want 'C:\path\to\my\dir\head.html'

Basically, what I want to achieve with this script is that it merges others static HTML pages into my page wherever I specify so with the <%% %%> marks.

Any ideas? Thank you.

1 Answers1

3

Try this:

@'
<%%head.html%%>
<body></body></html>
'@ > testFile.html

@'
<!DOCTYPE html>
<html><head><title></title></head>
'@ > head.html

$r = [regex]"<\%\%([\w.-_]+)\%\%>"
$fileContent = Get-Content testFile.html -Raw
$matchEval = {param($matchInfo)         
    $fileName = $matchInfo.Groups[1].Value
    Get-Content $fileName -Raw
}
$r.Replace($fileContent, $matchEval)

The second parameter is a MatchEvaluator callback which expects one parameter which is of type MatchInfo. Also, if you're on v3 you don't need to pipe through Out-String, you can just use the -Raw parameter on Get-Content.

BTW there is a way to do this if you have a function (not a scriptblock) called matchEval, that is:

$r.Replace($fileContent, $function:matchEval)
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • Thank you Keith, this is what I was looking for. I couldn't figure out the form of a proper callback but now I see it. Thanks. –  Jul 20 '13 at 21:26