Search code examples
powershellbatch-file

Powershell replace a string with percentages and quotations


I am struggling to get this powershell replace (command in a batch) text to work;

@echo off
pushd %~dp0
setlocal EnableDelayedExpansion

::enable PS commands in batch
set "Ps_Bypass=PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command"

set /p install=Add File1..(y)es (n)o:
if "%install%"=="n" %Ps_Bypass% "(gc "files.txt") -replace '%FILE1%="Install File One.zip"', ''" ^| Set-Content files.txt

If the user presses no, the entry %FILE1%="Install File One.zip" needs to be blanked from the files.txt, otherwise left leaving a list of chosen files for another program.

There are a few other lines the same just different file names.

I can get the command to blank any other words or strings (without unusual chars) in the files.txt so I know it will work but there is something in the string content causing a problem. There are no errors, it just doest blank the entry.

I have tried adding back ticks, back slashes, carrots in front of the %'s + = and also double quoting. The closest I got was to the Install File One.zip text being deleted but the %file1%= remained!

Been using this technique to replace text for a while in various things but this string with %+=+"" is giving me a headache!!

Any help, great appreaciated - thanks...


Solution

  • The issue is likely due to the special characters and the syntax within the PowerShell command.

    When using % within a PowerShell command in a batch script, you need to double the % sign (%%) so that variable is interpreted correctly. Also, you need to make sure that the strings and paths are properly quoted to avoid any issues with spaces or special characters. Changed script would look like this:

    @echo off
    pushd %~dp0
    setlocal EnableDelayedExpansion
    
    ::enable PS commands in batch
    set "Ps_Bypass=PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command"
    
    set /p install=Add File1..(y)es (n)o:
    
    if "%install%"=="n" (
        %Ps_Bypass% "(Get-Content 'files.txt') -replace '%%FILE1%%=\"Install File One.zip\"', '' | Set-Content 'files.txt'"
    )