IT박스

Windows에서 변수의 명령 결과를 어떻게 얻습니까?

itboxs 2020. 7. 14. 20:57
반응형

Windows에서 변수의 명령 결과를 어떻게 얻습니까?


Windows 배치 스크립트에서 변수로 명령 결과를 얻으려고합니다 ( bash 스크립트에 해당하는 bash 에서 명령 결과를 얻는 방법 참조 ). .bat 파일에서 작동하는 솔루션이 선호되지만 다른 일반적인 Windows 스크립팅 솔루션도 환영합니다.


모든 명령 출력을 캡처해야하는 경우 다음과 같은 배치를 사용할 수 있습니다.

@ECHO OFF
IF NOT "%1"=="" GOTO ADDV
SET VAR=
FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I
SET VAR
GOTO END

:ADDV
SET VAR=%VAR%!%1

:END

모든 출력 라인은 "!"로 구분 된 VAR에 저장됩니다.

@ 존 : 이것에 실용적인 용도가 있습니까? 스크립트 작업을 쉽게 수행 할 수있는 PowerShell 또는 다른 프로그래밍 언어 (Python, Perl, PHP, Ruby)를보아야한다고 생각합니다.


겸손 에 대한 명령은 지난 몇 년 동안 몇 가지 흥미로운 기능을 축적하고있다 :

D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008

"delims="date 명령의 출력이 한 번에 흐트러 지도록 기본 공간 및 탭 구분 기호 겹쳐 씁니다.

여러 줄로 된 출력을 캡처하려면 여전히 기본적으로 하나의 라이너가 될 수 있습니다 (결과 변수에서 변수 lf를 구분 기호로 사용).

REM NB:in a batch file, need to use %%i not %i
setlocal EnableDelayedExpansion
SET lf=-
FOR /F "delims=" %%i IN ('dir \ /b') DO if ("!out!"=="") (set out=%%i) else (set out=!out!%lf%%%i)
ECHO %out%

파이프 표현식을 캡처하려면 ^|다음을 사용하십시오 .

FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"

현재 디렉토리를 얻으려면 다음을 사용할 수 있습니다.

CD > tmpFile
SET /p myvar= < tmpFile
DEL tmpFile
echo test: %myvar%

임시 파일을 사용하고 있기 때문에 가장 예쁘지는 않지만 확실히 작동합니다! 'CD'는 현재 디렉토리를 'tmpFile'에 놓고 'SET'은 tmpFile의 내용을로드합니다.

다음은 "배열"을 사용하는 여러 줄에 대한 솔루션입니다.

@echo off

rem ---------
rem Obtain line numbers from the file
rem ---------

rem This is the file that is being read: You can replace this with %1 for dynamic behaviour or replace it with some command like the first example i gave with the 'CD' command.
set _readfile=test.txt

for /f "usebackq tokens=2 delims=:" %%a in (`find /c /v "" %_readfile%`) do set _max=%%a
set /a _max+=1
set _i=0
set _filename=temp.dat

rem ---------
rem Make the list
rem ---------

:makeList
find /n /v "" %_readfile% >%_filename%

rem ---------
rem Read the list
rem ---------

:readList
if %_i%==%_max% goto printList

rem ---------
rem Read the lines into the array
rem ---------
for /f "usebackq delims=] tokens=2" %%a in (`findstr /r "\[%_i%]" %_filename%`) do set _data%_i%=%%a
set /a _i+=1
goto readList

:printList
del %_filename%
set _i=1
:printMore
if %_i%==%_max% goto finished
set _data%_i%
set /a _i+=1
goto printMore

:finished

그러나 더 강력한 다른 쉘로 옮기거나이 응용 프로그램을위한 응용 프로그램을 만드는 것이 좋습니다. 배치 파일의 가능성을 상당히 늘리고 있습니다.


you need to use the SET command with parameter /P and direct your output to it. For example see http://www.ss64.com/nt/set.html. Will work for CMD, not sure about .BAT files

From a comment to this post:

That link has the command "Set /P _MyVar=<MyFilename.txt" which says it will set _MyVar to the first line from MyFilename.txt. This could be used as "myCmd > tmp.txt" with "set /P myVar=<tmp.txt". But it will only get the first line of the output, not all the output


Example to set in the "V" environment variable the most recent file

FOR /F %I IN ('DIR *.* /O:D /B') DO SET V=%I

in a batch file you have to use double prefix in the loop variable:

FOR /F %%I IN ('DIR *.* /O:D /B') DO SET V=%%I

Just use the result from the FOR command. For example (inside a batch file):

for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)

You can use the %%I as the value you want. Just like this: %%I.

And in advance the %%I does not have any spaces or CR characters and can be used for comparisons!!


If you're looking for the solution provided in Using the result of a command as an argument in bash?

then here is the code:

@echo off
if not "%1"=="" goto get_basename_pwd
for /f "delims=X" %%i in ('cd') do call %0 %%i
for /f "delims=X" %%i in ('dir /o:d /b') do echo %%i>>%filename%.txt
goto end

:get_basename_pwd
set filename=%~n1

:end
  • This will call itself with the result of the CD command, same as pwd.
  • String extraction on parameters will return the filename/folder.
  • Get the contents of this folder and append to the filename.txt

[Credits]: Thanks to all the other answers and some digging on the Windows XP commands page.


@echo off

ver | find "6.1." > nul
if %ERRORLEVEL% == 0 (
echo Win7
for /f "delims=" %%a in ('DIR "C:\Program Files\Microsoft Office\*Outlook.EXE" /B /P /S') do call set findoutlook=%%a
%findoutlook%
)

ver | find "5.1." > nul
if %ERRORLEVEL% == 0 (
echo WinXP
for /f "delims=" %%a in ('DIR "C:\Program Files\Microsoft Office\*Outlook.EXE" /B /P /S') do call set findoutlook=%%a
%findoutlook%
)
echo Outlook dir:  %findoutlook%
"%findoutlook%"

I would like to add a remark to the above solutions:

All these syntaxes work perfectly well IF YOUR COMMAND IS FOUND WITHIN THE PATH or IF THE COMMAND IS A cmdpath WITHOUT SPACES OR SPECIAL CHARACTERS.

But if you try to use an executable command located in a folder which path contains special characters then you would need to enclose your command path into double quotes (") and then the FOR /F syntax does not work.

Examples:

$ for /f "tokens=* USEBACKQ" %f in (
    `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" Hello '"F:\GLW7\Distrib\System\Shells and scripting"'`
) do echo %f
The filename, directory name, or volume label syntax is incorrect.

or

$ for /f "tokens=* USEBACKQ" %f in (
      `"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'F:\GLW7\Distrib\System\Shells' is not recognized as an internal or external command, operable program or batch file.

or

`$ for /f "tokens=* USEBACKQ" %f in (
     `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello' is not recognized as an internal or external command, operable program or batch file.

In that case, the only solution I found to use a command and store its result in a variable is to set (temporarily) the default directory to the one of command itself :

pushd "%~d0%~p0"
FOR /F "tokens=* USEBACKQ" %%F IN (
    `FOLDERBROWSE "Hello world!" "F:\GLW7\Distrib\System\Layouts (print,display...)"`
) DO (SET MyFolder=%%F)
popd
echo My selected folder: %MyFolder%

The result is then correct:

My selected folder: F:\GLW7\Distrib\System\OS install, recovery, VM\
Press any key to continue . . .

Of course in the above example, I assume that my batch script is located in the same folder as the one of my executable command so that I can use the "%~d0%~p0" syntax. If this is not your case, then you have to find a way to locate your command path and change the default directory to its path.

NB: For those who wonder, the sample command used here (to select a folder) is FOLDERBROWSE.EXE. I found it on the web site f2ko.de (http://f2ko.de/en/cmd.php).

If anyone has a better solution for that kind of commands accessible through a complex path, I will be very glad to hear of it.

Gilles


You can capture all output in one variable, but the lines will be separated by a character of your choice (# in the example below) instead of an actual CR-LF.

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%i in ('dir /b') do (
    if "!DIR!"=="" (set DIR=%%i) else (set DIR=!DIR!#%%i)
)
echo directory contains:
echo %DIR%

Second version, if you need to print the contents out line-by-line. This takes advanted of the fact that there won't be duplicate lines of output from "dir /b", so it may not work in the general case.

@echo off
setlocal EnableDelayedExpansion
set count=0
for /f "delims=" %%i in ('dir /b') do (
    if "!DIR!"=="" (set DIR=%%i) else (set DIR=!DIR!#%%i)
    set /a count = !count! + 1
)

echo directory contains:
echo %DIR%

for /l %%c in (1,1,%count%) do (
    for /f "delims=#" %%i in ("!DIR!") do (
        echo %%i
        set DIR=!DIR:%%i=!
    )
)

@echo off
setlocal EnableDelayedExpansion
FOR /F "tokens=1 delims= " %%i IN ('echo hola') DO (
    set TXT=%%i
)
echo 'TXT: %TXT%'

the result is 'TXT: hola'


You should use the for command, here is an example:

@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"

and you can use call :output "Command goes here" then the output will be in the %output% variable.

Note: If you have a command output that is multiline, this tool will set the output to the last line of your multiline command.


Please refer to this http://technet.microsoft.com/en-us/library/bb490982.aspx which explains what you can do with command output.

참고URL : https://stackoverflow.com/questions/108439/how-do-i-get-the-result-of-a-command-in-a-variable-in-windows

반응형