Assign output of a program to a variable using a MS batch file

前端 未结 10 950
梦谈多话
梦谈多话 2020-11-22 10:06

I need to assign the output of a program to a variable using a MS batch file.

So in GNU Bash shell I would use VAR=$(application arg0 arg1). I need a si

10条回答
  •  一个人的身影
    2020-11-22 11:05

    Some macros to set the output of a command to a variable/

    For directly in the command prompt

    c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"
    
    c:\>assign WHOAMI /LOGONID,my-id
    
    c:\>echo %my-id%
    

    Macro with arguments

    As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

    @echo off
    
    ::::: ---- defining the assign macro ---- ::::::::
    setlocal DisableDelayedExpansion
    (set LF=^
    %=EMPTY=%
    )
    set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
    
    ::set argv=Empty
    set assign=for /L %%n in (1 1 2) do ( %\n%
       if %%n==2 (%\n%
          setlocal enableDelayedExpansion%\n%
          for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
             for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
          ) %\n%
       ) %\n%
    ) ^& set argv=,
    
    ::::: -------- ::::::::
    
    
    :::EXAMPLE
    %assign% "WHOAMI /LOGONID",result
    echo %result%
    

    FOR /F macro

    not so easy to read as the previous macro.

    ::::::::::::::::::::::::::::::::::::::::::::::::::
    ;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
    ;;set "--=') do @set ""                        &::
    ;;set "}}==%%#""                               &::
    ::::::::::::::::::::::::::::::::::::::::::::::::::
    
    :: --examples
    
    ::assigning ver output to %win-ver% variable
    %{{% ver %--%win-ver%}}%
    echo 3: %win-ver%
    
    
    ::assigning hostname output to %my-host% variable
    %{{% hostname %--%my-host%}}%
    echo 4: %my-host%
    

    Macro using a temp file

    Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

    @echo off
    
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    
    chcp %[[%code-page%]]%
    echo ~~%code-page%~~
    
    whoami %[[%its-me%]]%
    echo ##%its-me%##
    

提交回复
热议问题