Skip to main content

How to URL Encode a String in Batch Script

URL encoding (or percent-encoding) is the process of converting special characters (like spaces, &, ?, /) into a format that can be safely included in a URL. For example, the space character is converted to %20. This is an essential step when constructing URLs for web requests or API calls. However, this is an advanced text-manipulation task for which Windows Batch has no native, reliable solution.

This guide will explain why a "pure-batch" approach is not feasible and demonstrate the definitive, modern method using a PowerShell one-liner. This is the only recommended approach for its correctness, power, and simplicity.

The Challenge: Why Pure Batch is Not a Viable Solution

Attempting to perform URL encoding in a pure batch script is a classic trap. While you could replace a few simple characters (SET "VAR=%VAR: =%20%"), the approach completely breaks down for several reasons:

  • The % Character: The most critical problem is the percent sign (%) itself. This character must be encoded as %25. However, % is the special character used for variable expansion in batch. Trying to replace it (SET "VAR=%VAR:%=%25%") results in a syntax error. There is no reliable, clean way around this fundamental conflict.
  • Complexity: A complete solution would require a long and fragile chain of SET commands for dozens of different special characters.
  • It's a Solved Problem: More powerful tools that are built into Windows have already solved this problem correctly.

For these reasons, a pure-batch approach is not just difficult; it's effectively impossible to do correctly and should be avoided.

The correct and professional way to handle this task is to call PowerShell, which has direct access to the .NET Framework's powerful networking and web utilities. The [System.Net.WebUtility] class is the modern, standard tool for this.

This command can be called directly from your batch script: powershell -Command "[System.Net.WebUtility]::UrlEncode('Your String Here')"

  • [System.Net.WebUtility]: The .NET class that contains web-related helper functions.
  • ::UrlEncode(): A static method within that class that performs the encoding according to web standards.

This method is fast, accurate, and handles all special characters correctly.

Basic Example: Encoding a Search Query

Let's encode the string "reports & invoices? (Q4)" to see how both spaces and special characters are handled.

@ECHO OFF
SET "QueryString=reports & invoices? (Q4)"
SET "EncodedString="

ECHO Original String: "%QueryString%"
ECHO.

FOR /F "delims=" %%V IN (
'powershell -Command "[System.Net.WebUtility]::UrlEncode('%QueryString%')"'
) DO (
SET "EncodedString=%%V"
)

ECHO PowerShell Method Result: %EncodedString%

In the following output, PowerShell correctly converts the spaces and all the special symbols.

Original String: "reports & invoices? (Q4)"

PowerShell Method Result: reports+%26+invoices%3F+%28Q4%29
note

UrlEncode traditionally converts spaces to +. This is valid. If you specifically need %20, you can do an extra replace: ...UrlEncode(...).Replace('+', '%20')

How the PowerShell Method Works

The one-liner is a direct command to the PowerShell engine.

  1. powershell -Command "...": This executes the command string without opening an interactive PowerShell window.
  2. [System.Net.WebUtility]::UrlEncode('...'): This calls the static UrlEncode method from the WebUtility class, passing it our string.
  3. The method processes the string, identifies all characters that are not "URL-safe" (A-Z, a-z, 0-9, -, _, ., ~), and converts them to their %HH hexadecimal representation.
  4. The final, encoded string is written to standard output, which the FOR /F loop in our batch script then captures into a variable.

Common Pitfalls and How to Solve Them

Problem: The String Contains Batch Special Characters

If your batch variable contains characters like & or |, cmd.exe might try to interpret them before passing the command to PowerShell.

Solution: Quoting. The example script uses single quotes inside the PowerShell command ('...'%QueryString%'...') which is generally robust. If your string contains single quotes, this can become tricky, but for most cases, this pattern works well.

Problem: PowerShell Execution Policy Issues

While less common for the -Command switch, a system's PowerShell Execution Policy can sometimes interfere with scripts.

Solution: For maximum reliability, especially in controlled environments, it's a good practice to include the -ExecutionPolicy Bypass flag.

FOR /F "delims=" %%V IN (
'powershell -NoProfile -ExecutionPolicy Bypass -Command "..."'
) DO ( ... )

Practical Example: Constructing a URL for an API Call

This script takes a search term from the user, correctly encodes it, and builds a full URL ready to be used with a tool like curl or passed to a browser.

@ECHO OFF
SETLOCAL
SET "BaseUrl=https://www.google.com/search?q="
SET "SearchTerm="

ECHO --- URL Constructor ---
ECHO.
SET /P "SearchTerm=Enter your search query: "

SET "EncodedTerm="
FOR /F "delims=" %%V IN (
'powershell -Command "[System.Net.WebUtility]::UrlEncode('%SearchTerm%')"'
) DO (
SET "EncodedTerm=%%V"
)

SET "FinalUrl=%BaseUrl%%EncodedTerm%"

ECHO.
ECHO Your final, encoded URL is:
ECHO %FinalUrl%

REM You could now use this URL, for example:
REM START "" "%FinalUrl%"

ENDLOCAL

Conclusion

URL encoding is a complex task where the native capabilities of batch scripting are insufficient.

  • A pure-batch solution is not feasible due to the inescapable conflict with the % character and the sheer complexity of the task.
  • The PowerShell [System.Net.WebUtility]::UrlEncode() method is the only correct and recommended solution. It is built for this exact purpose, adheres to web standards, and is easily integrated into any batch script.

For any task that requires constructing a valid URL, the PowerShell one-liner is the professional, reliable, and efficient choice.