EN VI

How to use special characters in a powerShellScript?

2024-03-11 05:30:07
How to use special characters in a powerShellScript

So I am trying to use the below script do dynamically put different values in a properties file But powershell will not let me use special characters such as !

@echo off
setlocal enabledelayedexpansion

rem Set the properties file path
set "PROPERTIES_FILE=src\main\resources\config.properties"

rem Replace placeholders with Jenkins parameters in the properties file
powershell -Command "(Get-Content '%PROPERTIES_FILE%') | ForEach-Object { $_ -replace 'USERNAME=(.*)', 'USERNAME=%Username%' } | Set-Content '%PROPERTIES_FILE%'"
powershell -Command "(Get-Content '%PROPERTIES_FILE%') | ForEach-Object { $_ -replace 'PASSWORD=(.*)', ('PASSWORD=' + [regex]::escape('%Password%')) } | Set-Content '%PROPERTIES_FILE%'"


rem Optionally, print the updated file contents for verification
type "%PROPERTIES_FILE%"

rem Execute your Maven command
mvn clean test -Dtest=ScriptTest

I am trying to use Jenkins parameters to update a config.properties file.

Solution:

Remove enabledelayedexpansion from your setlocal statement.

  • In other words: Replace line setlocal enabledelayedexpansion with just setlocal

enabledelayedexpansion is what "eats" the ! characters - even those present in the values of statically referenced variables, such as %Password%.

enabledelayedexpansion is only needed if you no need dynamic variable expansion, by enclosing variable references in !...!, e.g. !Password!, as distinct from the static, macro-like expansion that regular %...% variable references perform.

While the enabledelayedexpansion feature is sometimes necessary, e.g. for building up a variable's value iteratively in a for /f statement, it is problematic for interpreting any ! as being part of a dynamic variable references, and quietly removing it if it isn't.

The following batch-file content demonstrates this problem:

@echo off
setlocal enableDelayedExpansion

:: In literal use, you CAN escape "!""
echo [hi^^!]
echo "[hi^!]"

echo --

:: Via variable references, you can NOT.

set "FOO=hi!"

echo [%FOO%]
echo [!FOO!]

The above outputs the following, proving that stand-alone ! can be escaped in literal use, but in variable values are quietly removed:

[hi!]
"[hi!]"
[hi]
[hi]

Note:

  • Variable references - both static and dynamic - permit a substitution (substring replacement) technique: e.g,
    set FOO=BAR_NONE, followed by echo %FOO:_=-% or echo !FOO:_=-! (with enabledelayedexpansion in effect) result in BAR-NONE.

  • However, with enabledelayedexpansion in effect this does NOT work for ! characters from what I can tell, no matter how many instances of ^, cmd.exe's escape character you place on either side of : in order to effect escaping of !

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login