user310291
user310291

Reputation: 38190

Powershell cannot expand this javascript content

Applying the answer to my previous question How to expand file content with powershell

I stumbled upon a fatal error when trying to expand this :

test.js:

<script type="text/javascript">
    $('.mylink').click(function(event) {
        var hash = $(this).attr("href");
    });
    // $var
</script>  

test.ps1

$test = get-content -raw test.html
$var = "test"

# Write to output file using UTF-8 encoding *without a BOM*.
[IO.File]::WriteAllText(
  "$PWD/out.html",
  $ExecutionContext.InvokeCommand.ExpandString($test)
)

Upvotes: 0

Views: 40

Answers (1)

woxxom
woxxom

Reputation: 73556

$ is a special symbol in PowerShell and $() denotes an inlined expression expanded with its contents so you'll need to escape it before expansion by adding a backtick ` before $(:

$ExecutionContext.InvokeCommand.ExpandString(($test -replace '\$\(', '`$('))

However, if you use PowerShell's $() in the template then it's a problem that would require a smarter replacement and probably much more complex algorithm to differentiate between jQuery and PS.

Upvotes: 2

Related Questions