简体   繁体   中英

How to use a variable in powershell replace command (from Windows CMD)

I'm currently using the following command to do a find and replace in a file (I googled the code and just added the -encoding UTF8 because otherwise Apache refused to read the file as a php file):

powershell -Command "(gc app.php) -replace '/../', '/../new_project_name/' | Out-File -encoding UTF8 app.php"

The code is working as long as the folder is "new_project_name". new_project_name should actually be a variable name though. Eg if SET new_project_name=example then the powershell would be as follows:

powershell -Command "(gc app.php) -replace '/../', '/../example/' | Out-File -encoding UTF8 app.php"

I've tried passing a variable to the powershell command but either get errors or no changes are made.

Variables defined in your batch script are available in the env: scope in PowerShell commands started from the batch script (as it inherits the parent script's environment):

Set "new_name=example"
powershell -Command "(gc app.php) -replace '/../', \"/../$env:new_name/\" | ..."

Note that if you use the variable inside a (PowerShell) string you must put that string in double quotes. Single quotes will not work. Escape the nested double quotes with backslashes for CMD.

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