Batch - Converting variable to uppercase

前端 未结 8 1712
一向
一向 2020-12-02 01:39

How would I go about changing the destl variable to uppercase before it is used. I assume some sort of character swap, however I couldn\'t get it working. C

8条回答
  •  -上瘾入骨i
    2020-12-02 02:26

    The shortest way (without requiring 3rd party downloads) would be to use PowerShell.

    set "str=The quick brown fox"
    for /f "usebackq delims=" %%I in (`powershell "\"%str%\".toUpper()"`) do set "upper=%%~I"
    

    A faster way but still using less code than any pure batch solution would be to employ WSH.

    @if (@CodeSection == @Batch) @then
    @echo off & setlocal
    
    set "str=The quick brown fox"
    for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%str%"') do set "upper=%%~I"
    set upper
    goto :EOF
    
    @end // end Batch / begin JScript hybrid
    WSH.Echo(WSH.Arguments(0).toUpperCase());
    

    And of course, you can easily make either a function so you can call it multiple times as needed.

    @if (@CodeSection == @Batch) @then
    @echo off & setlocal
    
    call :toUpper upper1 "The quick brown fox"
    call :toUpper upper2 "jumps over the lazy dog."
    set upper
    goto :EOF
    
    :toUpper  
    for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%~2"') do set "%~1=%%~I"
    goto :EOF
    
    @end // end Batch / begin JScript hybrid
    WSH.Echo(WSH.Arguments(0).toUpperCase());
    

    Or if you want to be really hacksy about it, you could abuse the tree command's error message like this:

    @echo off & setlocal
    
    set upper=
    set "str=Make me all uppercase!"
    for /f "skip=2 delims=" %%I in ('tree "\%str%"') do if not defined upper set "upper=%%~I"
    set "upper=%upper:~3%"
    echo %upper%
    

提交回复
热议问题