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.

4

1 回答 1

3

尝试这个:

@'
<%%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)

第二个参数是一个 MatchEvaluator 回调,它需要一个 MatchInfo 类型的参数。此外,如果您使用的是 v3,则不需要通过管道Out-String,您只需使用-Raw参数 on Get-Content

顺便说一句,如果您有一个名为 matchEval的函数(不是脚本块),那么有一种方法可以做到这一点,即:

$r.Replace($fileContent, $function:matchEval)
于 2013-07-20T19:09:38.937 回答