如何在 Windows 批处理脚本中将 %USERNAME% 的值转换为小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/284776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 05:42:26  来源:igfitidea点击:

How to convert the value of %USERNAME% to lowercase within a Windows batch script?

windowsscriptingbatch-filecmd

提问by Nano Taboada

I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a *NIX box, I'm facing the eternal case problem between these two worlds.

我正在使用 dot bat 脚本自动化一些源代码控制软件功能,但鉴于我们的 svn 存储库托管在 *NIX 框中,我面临着这两个世界之间永恒的案例问题。

Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?

是否有任何 cmd.exe 函数可以将 Windows 系统变量 %USERNAME% 的值转换为小写?

Thanks much in advance!

非常感谢!

采纳答案by Mauro

a quick google found this...

一个快速的谷歌发现了这个......

@echo off
goto :end_remarks
*************************************************************************************
*
*
*    authored:Sam Wofford
*    Returns lowercase of a string
*    12:13 PM 11/13/02
**************************************************************************************
:end_remarks
setlocal
set errorlevel=-1
if {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit
if {%1}=={/?} call :Help &goto :endit
call :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z

:start
set input=%1
set input=%input:"=%
set totparams=0
call :COUNT_PARAMS %input%
call :MAKE_LOWERCASE %input%
set errorlevel=
echo %convertedstring%
endlocal
goto :eof
:endit
echo %errorlevel%
endlocal
goto :eof

:MAKE_LOWERCASE
:nextstring
if {%1}=={} goto :eof
set string=%1
set /a params+=1
set STRINGCONVERTED=
set pos=0
:NEXT_CHAR
set onechar=%%string^:^~%pos%,1%%
for /f "tokens=1,2 delims==" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c
if not defined STRINGCONVERTED goto :NEXT_CHAR
shift /1
if %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end
goto :nextstring
goto :eof

:Help
echo USAGE:%~n0 string OR %~n0 "with spaces"
echo function returns the lowercase of the string or -1 (error)
echo strings with embedded spaces needs to be in quotes Ex. "lower case"
echo in a batch NTscript "for /f %%%%A in ('lcase STRING') do set var=%%%%A"
set errorlevel=
goto :eof

:checkit
set LCFOUND=
if /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof
set char=%1
for /f "tokens=2 delims=_=" %%A in ('set LCASE_') do call :findit %%A %char%
:skipit
if defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)
set /a pos+=1
goto :eof

:set_LCASE_array
:setit
if {%1}=={} goto :eof
set LCASE_%1_=%1
SHIFT /1
goto :setit

:findit
if defined LCFOUND goto :eof
set ucletter=%1
set lcchar=%2
if /i {%ucletter%}=={%lcchar%} set LCFOUND=yes
goto :eof

:COUNT_PARAMS
:COUNTPARAMS
if {%1}=={} goto :eof
set /a totparams+=1
shift /1
goto :COUNTPARAMS 

add that as a file (lowercase.cmd) to your path and you should be able to call it as "Lowercase.cmd %Username%", you could pipe it into another command if needed.

将其作为文件 (lowercase.cmd) 添加到您的路径中,您应该能够将其称为“Lowercase.cmd %Username%”,如果需要,您可以将其通过管道传输到另一个命令中。

回答by Dharma Leonardi

Well, I was browsing for some syntax and stumbled upon this page. I know its old but I thought I'd take a break and give the brain a little kick.

好吧,我正在浏览一些语法并偶然发现了这个页面。我知道它很旧,但我想我会休息一下,给大脑一点刺激。

Here's something a little shorter and manageable. This just "brute forces" all uppercase letters to lowercase letters without regards to whether the actual letter exists in the string or not. Thus the functional loop runs exactly 26 times no matter the length of the string.

这里有一些更短且易于管理的内容。这只是“蛮力”将所有大写字母转换为小写字母,而不管字符串中是否存在实际字母。因此,无论字符串的长度如何,函数循环都会运行 26 次。

Hope this helps someone.

希望这可以帮助某人。

@echo off
cls
setlocal enabledelayedexpansion

REM ***** Modify as necessary for the string source. *****
set "_STRING=%*"
if not defined _STRING set "_STRING=%USERNAME%"
set _STRING
REM ***** Modify as necessary for the string source. *****

set "_UCASE=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "_LCASE=abcdefghijklmnopqrstuvwxyz"

for /l %%a in (0,1,25) do (
   call set "_FROM=%%_UCASE:~%%a,1%%
   call set "_TO=%%_LCASE:~%%a,1%%
   call set "_STRING=%%_STRING:!_FROM!=!_TO!%%
)

set _STRING
endlocal

Example:

例子:

E:\OS.ADMIN>LCASE.BAT The Quick Fox Jumps Over The Brown Fence.

Result:

结果:

_STRING=The Quick Fox Jumps Over The Brown Fence.
_STRING=the quick fox jumps over the brown fence.

回答by SumoRunner

download some unix utilities for DOS from http://short.stop.home.att.net/freesoft/unix.htmand use tr.exe (translate characters)

http://short.stop.home.att.net/freesoft/unix.htm下载一些用于 DOS 的 unix 实用程序 并使用 tr.exe(翻译字符)

echo %USERNAME% | tr "[A-Z]" "[a-z]" 

I also use a DOS extended cmd replacement named 4NT which has a built in command @lower

我还使用名为 4NT 的 DOS 扩展 cmd 替换,它具有内置命令 @lower

echo %@lower[%USERNAME%]

回答by Victor Mendon?a Nogueira

In my batch file I'm doing a comparsion between %USERNAME% and a CSV file.

在我的批处理文件中,我正在对 %USERNAME% 和 CSV 文件进行比较。

The program would not work if user was logged in UperCase username.

如果用户以大写用户名登录,该程序将无法运行。

Ex:
Login : GB2NOGU // Won't work
Login : gb2nogu // Works

例如:
登录:GB2NOGU // 不起作用
登录:gb2nogu //起作用

Here I could solve my problem doing a insensitive comparison.

在这里,我可以通过不敏感的比较来解决我的问题。

if /i %USERNAME%==gb2nogu (
     // Code here
)

The parameter /i tells the cmd to do a insensitive case comparison, so it'll ignore the difference between lowercase and uppercase letters.

参数 /i 告诉 cmd 进行不敏感的大小写比较,因此它将忽略小写和大写字母之间的差异。

回答by StackFi Neon

http://www.dzone.com/snippets/lowercasing-string-bat-files

http://www.dzone.com/snippets/lowercasing-string-bat-files

lower.bat

下.bat

echo>%1
dir /b/l %1>lower.tmp
set /p result=<lower.tmp
echo %result%

cmd

指令

lower "Mein BinnenMajuskel"

result

结果

mein binnenmajuskel

CAUTION: Quick & dirty, but also insecure and dangerous variant. Because you create two files. One called like the given string and another called lower.tmp, which contains the lowered string. What happens if you execute lower "UserName"in a directory, where this file or directory already exists? Especially if you delete this files afterwards ...

注意:快速和肮脏,但也不安全和危险的变体。因为你创建了两个文件。一个像给定的字符串一样调用,另一个称为lower.tmp,其中包含降低的字符串。如果你lower "UserName"在一个目录中执行,这个文件或目录已经存在,会发生什么?特别是如果你之后删除这些文件......

Improved version:

改良版:

echo>%Temp%\%1
dir /b/l %Temp%\%1>%Temp%\lower.tmp
set /p result=<%Temp%\lower.tmp
del %Temp%\%1
del %Temp%\lower.tmp

回答by LukStorms

When a scripting language is installed then that can be used with a "FOR" to set a variable.

安装脚本语言后,它可以与“FOR”一起使用来设置变量。

Any scripting language can be used if it can convert a string to lowercase and output the result.

如果可以将字符串转换为小写并输出结果,则可以使用任何脚本语言。

An example using Perl 5 :

使用 Perl 5 的示例:

@FOR /F %%s IN ('perl -e "print lc(pop)" %USERNAME%') DO @set USERNAME=%%s

An example using PowerShell :

使用 PowerShell 的示例:

@FOR /F %%s IN ('powershell -command "(get-item env:'USERNAME').Value.ToLower()"') DO @set USERNAME=%%s

These days, odds are that PowerShell is already installed by default.

如今,PowerShell 可能已经默认安装。

回答by Adolfo

:: UPcase.bat ==> Store in environment variable _UPcase_ the upper case of %1
:: -> Use quotes "" when the first argument has blanks or special characteres
::
:: Adapted from -> http://www.netikka.net/tsneti/info/tscmd039.htm
::
:: Note that the substitution method is case insensitive, which means that
:: while working for this application, it is not useful for all character
:: substitution tasks.
::
:: More concisely, one can capitalize (if you pardon the pun) on the fact
:: that in for and the substitution lower and upper case source are
:: equivalent.
@echo off

:: %~1 -> removes quotes from the first command line argument
:: http://steve-jansen.github.io/guides/windows-batch-scripting/part-2-variables.html
@echo off
::setlocal EnableExtensions
    :: echo %_UPcase_%
    call :ToUpcaseWithFor "%~1" _UPcase_
    :: echo %_UPcase_% _doit_1_
::endlocal & goto :EOF
goto :EOF
::
:: ======================
:ToUpcaseWithFor
setlocal EnableExtensions EnableDelayedExpansion
  set var_=%~1
  for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    set var_=!var_:%%c=%%c!
  )
endlocal & set %2=%var_%& goto :EOF

:EOF
:: UPcase.bat ==> EOF

回答by It Wasn't Me

This is the same answer /by @It Wasn't Mehere

这是相同的答案/ @这里不是我



For a predictive character set, this substring Set !var:A=a!works, and only working with predefined substringin bat/cmd.

对于预测字符集,此子字符串Set !var:A=a!有效,并且仅适用于bat/ cmd 中的预定义子字符串

For this type of task, why not get a little help with c#, which can make it possible to work with unconventional accents and consonants è, è, ?, ?, ?, ?, ?, ? etc.

对于这种类型的任务,为什么不使用c#获得一些帮助,它可以使用非常规的重音和辅音è, è, ?, ?, ?, ?, ?, ? 等等。

Where the bat/cmdwill generate c#code, it will be compiled and executed at run time ....

蝙蝠/ CMD将生成的C#代码,它会被编译并在运行时执行....

Which solves possible user inputs, in which the sequence comes with accents and the vowels/consonants are different from the conventional ones [a-z]and/or [A_Z]

这解决了可能的用户输入,其中序列带有重音并且元音/辅音不同于传统的[az]和/或[A_Z]



@echo off & setlocal EnableDelayedExpansion 

cd /d "%~dp0" && title <nul && title ...\%~dpnx0 /// !time:~0,8! !date!

if exist "%tmp%\ToUpLower.cs" 2>nul >nul del /q /f "%tmp%\ToUpLower.cs" 
set "_where=%__appdir__%where.exe" && set "_csc=%windir%\Microsoft.NET"
>"%temp%\ToUpLower.cs"  ( 
echo= using System; namespace SUQ1522019 ^{class Program ^{static void Main(string[] args^) ^{
echo= if (args.Length==2 ^&^& args[0].ToLower(^)=="-l"^) ^{Console.WriteLine(args[1].ToLower(^)^);^} 
echo= if (args.Length==2 ^&^& args[0].ToLower(^)=="-u"^) ^{Console.WriteLine(args[1].ToUpper(^)^);^}^}^}^}
)

set "_arg=/t:exe /out:"%tmp%\ToUpLower.exe" "%tmp%\ToUpLower.cs" /platform:anycpu "
for /f tokens^=* %%i in ('!_where! /r "!_csc!" "csc.exe"^|findstr /lic:"k\v2\." 
')do "%%~i" !_arg! /unsafe+ /w:0 /o /nologo

for /f tokens^=* %%U in ('"%tmp%\ToUpLower.exe" -u %USERNAME%')do set "_up_case=%%U"
for /f tokens^=* %%l in ('"%tmp%\ToUpLower.exe" -l %USERNAME%')do set "_low_case=%%l"

echo/  Your username upcase is: !_up_case!
echo/ Your username lowcase is: !_low_case!

echo/ >nul 2>nul copy "%tmp%\ToUpLower.exe" "." 
del /q /f "%tmp%\ToUpLower.*" >nul 2>nul && endlocal & goto :EOF


  • Outputs for %USERNAME%
  • 输出 %USERNAME%
 Your username upcase is: USERNAME
Your username lowcase is: username


The ToUpLower.csc#code with no escaping:

没有转义的c#代码:ToUpLower.cs



 using System; namespace SUQ1522019 {class Program {static void Main(string[] args) {
 if (args.Length==2 && args[0].ToLower()=="-l") {Console.WriteLine(args[1].ToLower());} 
 if (args.Length==2 && args[0].ToLower()=="-u") {Console.WriteLine(args[1].ToUpper());}}}}


The ToUpLower.csc#code with no escaping and indented:

没有转义和缩进的c#代码:ToUpLower.cs



using System
namespace SUQ1522019 
{
   class Program 
   {
      static void Main(string[] args)
      {
         if (args.Length==2 && args[0].ToLower()=="-l") 
         {
            Console.WriteLine(args[1].ToLower());
         } 

         if (args.Length==2 && args[0].ToLower()=="-u") 
         {
            Console.WriteLine(args[1].ToUpper());
         }
      }
   }
}


  • This c#code was compiled/testedon csc.exeversions:
  • c#代码已在版本上编译/测试csc.exe
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe
c:\Windows\Microsoft.NET\Framework\v3.5\csc.exe
c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe
c:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe
c:\Windows\Microsoft.NET\Framework64\v3.5\csc.exe
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe


  • This is the command lineused to compilethe c#code:
  • 这是命令行用于编译C#代码:
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /t:exe /out:"%tmp%\ToUpLower.exe" "%tmp%\ToUpLower.cs" /platform:anycpu /unsafe+ /w:0 /o /nologo 


  • ToUpLower.exeusageUPPER to -> lower
  • ToUpLower.exe使用UPPER 到 -> 较低
ToUpLower.exe -l STRING 

:: or ..

ToUpLower.exe -L STRING
ToUpLower.exe -l STRING 

:: or ..

ToUpLower.exe -L STRING



  • ToUpLower.exeusagelower to -> UPPER
  • ToUpLower.exe使用低至 -> UPPER


ToUpLower.exe -u string

:: or ..

ToUpLower.exe -U string
ToUpLower.exe -u string

:: or ..

ToUpLower.exe -U string



To keep ToUpLower.exe, remove echo/from copycommand:

要保留ToUpLower.exe,请echo/命令中删除:copy



echo/ >nul 2>nul copy "%tmp%\ToUpLower.exe" "." 

This command line will copy ToUpLower.exefrom %temp%to same the same folder where your bat is running.

此命令行复制会ToUpLower.exe%temp%你的蝙蝠正在哪里运行到同一个相同的文件夹。



Programming Guide C#:

C# 编程指南:



Sorry my limited English

抱歉我的英语有限

回答by npocmaka

Probably this is the fastest way to convert a string to lowercase in batch file as it uses macroand there are no temp files (it saves the produced string in variable called result):

这可能是在批处理文件中将字符串转换为小写的最快方法,因为它使用并且没有临时文件(它将生成的字符串保存在名为 的变量中result):

@echo off

set LowerCaseMacro=for /L %%n in (1 1 2) do if %%n==2 (for %%# in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do set "result=!result:%%#=%%#!") else setlocal enableDelayedExpansion ^& set result=

set "string=SOme STrinG WiTH lowerCAse letterS and UPCase leTTErs"
%LowerCaseMacro%%string%

echo %result%