将位置参数的值转换为变量(powershell)

时间:2013-07-20 16:30:40

标签: powershell scripting

在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 \到\ my \ dir \ head.html'

基本上,我想用这个脚本实现的是它将其他静态HTML页面合并到我的页面,无论我在哪里指定,所以使用&lt; %% %%&gt;标记。

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分: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上的Get-Content参数。

BTW有一种方法可以做到这一点,如果你有一个名为matchEval的函数(不是一个scriptblock),那就是:

$r.Replace($fileContent, $function:matchEval)
相关问题