cmd批处理脚本函数带返回值

问题描述 投票:0回答:1

我在

here
以及 stackoverflow 上找到了像 toUpper 这样的批处理文件字符串函数,但我不知道如何使用它们。我找到了几个例子和说明,其中一些是矛盾的,但出于某种原因,它们都不适合我。我如何在 .bat 文件中使用这样的函数?这是
toUpper
的示例代码:

@echo off
setlocal enabledelayedexpansion

:: Main script starts here
set "arg=exampleString"

:: Output the original
echo Original: %arg%

:: Call the toUpper function to convert %arg% to uppercase
call :toUpper arg

:: Output the result
echo Uppercase: %arg%


:toUpper str -- converts lowercase character to uppercase
if not defined %~1 EXIT /b
for %%a in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I"
            "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R"
            "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z" "ä=Ä"
            "ö=Ö" "ü=Ü") do (
    call set %~1=%%%~1:%%~a%%
)
EXIT /b

我得到的是这样的:

Original: exampleString
Uppercase: "ü=Ü"rg:ü=Ü

这是怎么回事?

batch-file cmd
1个回答
0
投票

几乎...

在子例程之前添加

goto :eof
,否则代码将意外地运行它。

第二:你已经启用了延迟扩展,所以使用它:

goto :eof
:toUpper str -- converts lowercase character to uppercase
if not defined arg EXIT /b
for %%a in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I"
            "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R"
            "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z" "ä=Ä"
            "ö=Ö" "ü=Ü" "ß=SS") do (
    set "%~1=!%~1:%%~a!"
)
EXIT /b 

由于元音变音,输出并不完全是您想要的。在脚本顶部添加

chcp 65001
以切换到可以处理它们的代码页。

我还建议添加

"ß=SS"
以确保语法正确。

© www.soinside.com 2019 - 2024. All rights reserved.