Search code examples
batch-filecmdwmicnetsh

Windows batch file variables containing whitespace/special chars inside a loop


Using this in a batch file on Windows 10:

@echo off
setlocal enabledelayedexpansion

set "profile=NetworkProfileName"
set result=

for /F "tokens=2 delims=: usebackq" %%F IN (`netsh wlan show profile %profile% key^=clear ^| findstr "Key Content"`) do (
  set "result=%%F"
)

echo %profile% has password:!result!
endlocal

I get the expected results:

NetworkProfileName has password: SuperSecretPassword

When I use a network profile name containing special characters and whitespace like this

set "profile=Wu-Tang LAN"

The profile is not found in the loop, and the password variable remains blank:

Wu-Tang LAN has password: 

If I run this command directly in cmd:

netsh wlan show profile "Wu-Tang LAN" key=clear | findstr "Key Content"

I get the expected output:

Key Content : OtherSecretPassword

Even ChatGPT 4 couldn't get me over the line! What is the secret?


Solution

  • If you had made any attempt to read the built-in documentation for net.exe, you'd have seen that the suggested syntax should have been wlan show profiles name="%profile%" key=clear, which not only clearly shows your profile name doublequoted, it also uses profiles not profile. If you next took a look at the built-in documentation for findstr.exe, you'd have noted that as you are wanting to match a space character, you should be using /C:"Key Content", to match those together.

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    Set "Profile=NetworkProfileName"
    
    Set "Key="
    For /F "Tokens=1,* Delims=:" %%G In ('%SystemRoot%\System32\netsh.exe WLAN Show
     Profiles Name^="%Profile%" Key^=Clear ^| %SystemRoot%\System32\findstr.exe /R
     /C:"Key Content" 2^>NUL') Do Set "Key=%%H"
    If Not Defined Key GoTo :EOF
    Set "Key=%Key:~1%"
    
    Echo %Profile% has password:%Key%
    Pause
    

    The idea above was designed not to use a space character as a delimiter just in case there is a possibility that the 'password' begins with a leading space character itself. You should also note that I have not enabled delayed expansion, which would cause issues if your 'password' included exclamation marks. It should be noted however, that should the password contain percent characters, you would need to perform extra work if you wanted to expand %Key% with Echo.