How to read a variable inside a powershell command written in a .bat file

Viewed 38

I have this bat file that i execute and it works great:

SET RPPROPERTIESPATH='C:\work\filepath.txt' //contains the word 'string1'

powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', 'string2' | Out-File -encoding ASCII %RPPROPERTIESPATH%"

But i want the replace param to come from a variable like so:

SET RPPROPERTIESPATH='C:\work\filepath.txt' //contains the word 'string1'
SET STRINGTOREPLACE='string3' 

 powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', %STRINGTOREPLACE% | Out-File -encoding ASCII %RPPROPERTIESPATH%"

This is not working, how should i make this work?

2 Answers

Set variables using set "varname=varvalue" syntax pattern and use them quoted if necessary like "%varname%" (for cmd) or like '%varname%' (for PowerShell). Then, your code snippet should be as follows:

SET "RPPROPERTIESPATH=C:\work\filepath.txt" //contains the word 'string1'
SET "STRINGTOREPLACE=string3"

powershell -Command "(gc '%RPPROPERTIESPATH%') -replace 'string1', '%STRINGTOREPLACE%' | Out-File -encoding ASCII '%RPPROPERTIESPATH%'"

Seems to work once i exclude the ' like so:

SET STRINGTOREPLACE=string3

 powershell -Command "(gc %RPPROPERTIESPATH%) -replace 'string1', '%STRINGTOREPLACE%' | Out-File -encoding ASCII %RPPROPERTIESPATH%"
Related