简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM