【问题标题】:Convert the value of a positional parameter into a variable (powershell)将位置参数的值转换为变量(powershell)
【发布时间】:2013-07-19 19:28:54
【问题描述】:

在 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 页面合并到我的页面中,无论我使用 标记。

有什么想法吗?谢谢。

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    试试这个:

    @'
    <%%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 进行管道传输,您可以在 Get-Content 上使用 -Raw 参数。

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

    $r.Replace($fileContent, $function:matchEval)
    

    【讨论】:

    • 谢谢基思,这就是我要找的。我无法弄清楚正确回调的形式,但现在我看到了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2019-03-11
    • 2012-06-09
    • 2021-08-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多