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

标签 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 \ 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/

相关文章:

bash - 如何使用 Bash 插入 SQLite 数据库?

mysql - 运行多个sql命令来归档和删除数据的最佳方法是什么

powershell - 在 Powershell 中使用 ffmpeg

powershell - 是否可以检查 Powershell 中是否给出了 -Verbose 参数?

powershell - 如何在执行本地命令时关闭powershell中的 ".\"?

powershell - 使用Powershell脚本以编程方式填写第三方登录屏幕

PowerShell:如何获得 if else 构造正确?

javascript - iMacros 是否支持 javascript 或任何其他脚本?

shell - zsh 运行存储在变量中的命令?

scripting - 如何在内联脚本中引用 Bamboo 工件?