在PowerShell 3中,我正在对字符串执行正则表达式替换,我想将'$ 1'位置参数作为变量传递给函数(请参见script.ps1的最后一行)
我的密码
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'));
问题出在script.ps1的最后一行,这是我找不到解决函数调用的方法,以便Get-Content从$ fileName获取正确的值。从错误消息中读取的内容为“$ 1”:
Get-Content : Cannot find path 'C:\path\to\my\dir\$1' because it does not exist.
我想要'C:\ path \ to \ my \ dir \ head.html'
基本上,我想用此脚本实现的目标是,它用<%% %%>标记将其他静态HTML页面合并到我指定的任何页面中。
有任何想法吗?谢谢。
最佳答案
试试这个:
@'
<%%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
上使用Get-Content
参数即可。顺便说一句,如果您有一个名为matchEval的函数(不是脚本块),则有一种方法可以做到这一点,即:
$r.Replace($fileContent, $function:matchEval)
关于powershell - 将位置参数的值转换为变量(powershell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764260/