0

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)
)
5
  • 2
    1) What's the question, and 2) what's the error? Commented Mar 1, 2017 at 22:22
  • $ is a special symbol in PS and $() denotes an inlined expression so you'll need to escape it before expansion: expandString(($test -replace '\$\(', '`$(')) Commented Mar 2, 2017 at 5:50
  • @wOxxOm how do you expand a powershell $var if you replace all $ ? Commented Mar 3, 2017 at 14:11
  • Hmm, vars isn't a problem because my suggestion is to replace $( which cannot be a part of an identifier. However, if you use PowerShell's $() then it's a problem that would require a smarter replacement algorithm to differentiate between jQuery and PS. Commented Mar 3, 2017 at 14:13
  • @wOxxOm thanks it works :) Commented Mar 3, 2017 at 14:21

1 Answer 1

2

$ 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand why it works except for app.controller('Ctrl', function($scope, $window, $sce) {} which gives empty var for $scope, $windows and $sce: app.controller('Ctrl', function(, , ) {}
Your original question is about preventing expansion of $() expressions which is why the answer deals only with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.