cmd:函数结果无法使用

时间:2017-11-18 23:06:16

标签: function cmd

我正在尝试创建.cmd文件。在我的代码中,我有一个被调用函数的结果。我能够回显结果,但是我没有使用结果或将其设置为新变量?

这是我的代码:

@echo off

:get_str
SET /P "str=String: " || SET str=nul
SET len=5
SET pl=false
CALL :pad_str pad_str str len pl
ECHO %pad_str%

ECHO.
GOTO :end

:pad_str <result> <str> <len> <pad_left>
(
    PAUSE>nul | ECHO -- .pad_str --
    SETLOCAL EnableDelayedExpansion
    SET str=!%~2!
    SET len=!%~3!
    SET pl=!%~4!
    CALL :str_len result str
    ECHO !result!
REM      ^^^^^^^^ This is giving me a number as expected.

    SET stl=!result!
    ECHO %stl%
REM      ^^^^^ This is the part that is returning the "ECHO is off." text. 

REM    IF %stl% EQU %len% DO GOTO :end_pad_str     <-- These are killing the program
REM    IF %stl% GTR %len% GOTO :trim_str           <-- because %stl% is empty.
REM    IF %stl% LSS %len% GOTO :sln_less_than_len  <--

    :trim_str
    PAUSE>nul | ECHO -- .trim_str --
    GOTO :end_pad_str

    :sln_less_than_len
    PAUSE>nul | ECHO -- .sln_less_than_len --
    GOTO :end_pad_str

    :end_pad_str
    PAUSE>nul | ECHO -- .end_pad_str --
)
(
    ENDLOCAL
    SET "%~1=%str%"
    EXIT /B
)

:str_len <result> <str>
(
    SETLOCAL EnableDelayedExpansion
    SET str=!%~2!#
    SET len=0
    FOR %%p IN (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) DO (
        IF "!str:~%%p,1!" NEQ "" ( 
            SET /A "len+=%%p"
            SET "str=!str:~%%p!"
        )
    )
)
(
    ENDLOCAL
    SET %~1=%len%
    EXIT /B
)

:end
PAUSE>nul | ECHO -- END --

注意:我也尝试过:

SET stl=%result%
SET stl=%%result%%
SET stl=!result:~0,-0!
SET stl=%result:~0,-0%`

所有这些都同样存在问题。

这是运行时的输出:

String: asdfasd
7
ECHO is off.
asdfasd

-- .end --

导致此问题的原因是什么?如何绕过它?

0 个答案:

没有答案