user3299182
user3299182

Reputation: 601

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

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?

Upvotes: 2

Views: 58

Answers (2)

JosefZ
JosefZ

Reputation: 30123

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%'"

Upvotes: 1

user3299182
user3299182

Reputation: 601

Seems to work once i exclude the ' like so:

SET STRINGTOREPLACE=string3

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

Upvotes: 0

Related Questions