3

I need to replace a simple string in a minified .js file after a successful build in VS2010.

So I'm trying to run a simple command line call from the Post-build events window.

This example, from here: https://blogs.technet.com/b/heyscriptingguy/archive/2008/01/17/how-can-i-use-windows-powershell-to-replace-characters-in-a-text-file.aspx totally mangulates the resulting .js file. Something is wrong, I suspect it is coming across some weird chars in my minified .js file that screws it up.

(Get-Content C:\Scripts\Test.js) | 
Foreach-Object {$_ -replace "// Old JS comment", "// New JS comment"} | 
Set-Content C:\Scripts\Test.js

How can I achieve such a simple task like I could do in unix in a single line..?

Aaron
  • 1,802
  • 3
  • 23
  • 50

1 Answers1

4

It would be great to see the diff file. Without more info, some info:

  • Set-Content adds a new empty line at the end (probably not a problem for you)
  • You can use -replace operator like this:

    (gc C:\Scripts\Test.js) -replace 'a','b' | sc C:\Scripts\Test.js

    -replace works on arrays too.

  • You could read the content via [io.file]::ReadAllText('c:\scripts\test.js') and use-replace`, but again, I don't think there will be significant difference.

Edit:

Double quotes are used when evaluating the string. Example:

$r = 'x'
$a = 'test'
'beg',1,2,"3x",'4xfour','last' -replace "1|$r","$a"

gives

beg
test
2
3test
4testfour
anything

To save the content with no ending new line, just use [io.file]::WriteAllText

$repl = (gc C:\Scripts\Test.js) -replace 'a','b' -join "`r`n"
[io.file]::WriteAllText('c:\scripts\test.js', $repl)
stej
  • 28,745
  • 11
  • 71
  • 104
  • Thanks for your help. Getting there. The single quotes stopped the files becoming mangulated! Yay. Is there any way to prevent the annoying blank link being created at the end of the file? – Aaron Feb 25 '11 at 11:25
  • That is bloody getting there now. Thanks!! Now for extra points: Can the $repl and [io.file] lines be combine into a single line? – Aaron Feb 25 '11 at 11:44
  • Sure:) `[io.file]::WriteAllText('c:\scripts\test.js', ((gc C:\Scripts\Test.js) -replace 'a','b' -join "`r`n"))` – stej Feb 25 '11 at 11:50
  • 2
    You are a genius and I love you! – Aaron Feb 25 '11 at 11:55
  • in Xml file how can I replace two paths like I want to set these two paths on Post Build, I would appreciate your help – dnxit Jun 24 '18 at 13:43