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)
)
Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487
  • 2
    1) What's the question, and 2) what's the error? – Bill_Stewart Mar 01 '17 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 '\$\(', '`$('))``` – wOxxOm Mar 02 '17 at 05:50
  • @wOxxOm how do you expand a powershell $var if you replace all $ ? – user310291 Mar 03 '17 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. – wOxxOm Mar 03 '17 at 14:13
  • @wOxxOm thanks it works :) – user310291 Mar 03 '17 at 14:21

1 Answers1

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.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • 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(, , ) {} – user310291 Mar 03 '17 at 15:33
  • Your original question is about preventing expansion of `$()` expressions which is why the answer deals only with that. – wOxxOm Mar 03 '17 at 15:36