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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

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?
That is bloody getting there now. Thanks!! Now for extra points: Can the $repl and [io.file] lines be combine into a single line?
Sure:) [io.file]::WriteAllText('c:\scripts\test.js', ((gc C:\Scripts\Test.js) -replace 'a','b' -join "rn"))
You are a genius and I love you!
in Xml file how can I replace two paths like <project outputDir="outputPath" baseDir="basePath" xmlns="confuser.codeplex.com"> I want to set these two paths on Post Build, I would appreciate your help

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.