home
PowerShell Replace text in files
Author Nigel Rivett
This iterates through all files in the source folder and subfolders, replaces the text then outputs to the file in the output folder.
It creates the output folder structure and files
Set the various variables in the bat file.
It copies the folder structure using xcopy
Iterates over all the files in the source folder using a command line for loop
For each file, calls a subroutine
The subroutine uses powershell to replace text and output to the output file in the output folder
Uses get-content, replace, set-content
The main issues are dealing with control characters, how to use variable and the number of escaped quotes needed in creating the command
Copy the below into a .bat file
set the variables InpDir, OutDir, InpStr, OutStr
Notes:
For multiline variables concatenate with `r`n
In OutStr use 6 double quotes to get a single double quote in the output file
Run the .bat and it will make a copy of all the folders and files replacing InpStr with OutStr
set InpDir=InFolder\WebSite
set OutDir=OutFolder\WebSite
set InpStr="<AdsenseScriptTest>"
set OutStr="<script async src=""""""//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js""""""></script>
set OutStr=%OutStr%%`r`n<!-- 728x15, created 24/05/08 -->
set OutStr=%OutStr%%`r`n<ins class=""""""adsbygoogle""""""
set OutStr=%OutStr%%`r`n style=""""""display:inline-block;width:728px;height:15px""""""
set OutStr=%OutStr%%`r`n data-ad-client=""""""ca-pub-3389506251366754""""""
set OutStr=%OutStr%%`r`n data-ad-slot=""""""xxxxxxxxxx""""""></ins>
set OutStr=%OutStr%%`r`n<script>
set OutStr=%OutStr%%`r`n(adsbygoogle = window.adsbygoogle || []).push({});
set OutStr=%OutStr%%`r`n</script>"
rem copy folder structure
xcopy %InpDir% %OutDir% /t /e /y
rem for each file in folder and sub folders
for /r %InpDir%\ %%a in (*.*) do call :subr "%%a"
goto:EOF
:subr
rem set input and output file names
set InpFile=%1
call set OutFile=%%InpFile:%InpDir%=%OutDir%%%
rem copy the input file to the output file replacing the required text
set pwscmd="(get-content """%InpFile%""").replace("""%InpStr%""","""%OutStr%""") | set-content """%OutFile%""""
powershell %pwscmd%
goto:EOF
home