How can I get the current width of the windows console in an environment variable within a batch file?
I like the approach using the built-in mode command in Windows.
Try the following batch-file:
#echo off
for /F "usebackq tokens=2* delims=: " %%W in (`mode con ^| findstr Columns`) do set CONSOLE_WIDTH=%%W
echo Console is %CONSOLE_WIDTH% characters wide
Note that this will return the size of the console buffer, and not the size of the window (which is scrollable).
If you wanted the height of the windows console, you can replace Columns in the findstr expression with Lines. Again, it will return the height of the buffer, not the window... I personally like to have a big buffer to allow scrolling back through history, so for me the Lines usually reports about 3000 :)
Just for fun, here's a version that doesn't use findstr to filter the output... in case (for some reason) you have a dislike of findstr:
#echo off
for /F "usebackq tokens=1,2* delims=: " %%V in (`mode con`) do (
if .%%V==.Columns (
set CONSOLE_WIDTH=%%W
goto done
)
)
:done
echo Console is %CONSOLE_WIDTH% characters wide
Note, this was all tried in Windows XP SP3, in a number of different windows (including one executing FAR manager).
try this (language/locale/.net independent):
#ECHO OFF
SET "ConsoleWidth="
SET /A LINECOUNT=0
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=1,2,*" %%A IN ('mode con') DO (SET /A LINECOUNT=!LINECOUNT!+1&IF !LINECOUNT! EQU 4 SET ConsoleWidth=%%B)
SETLOCAL DISABLEDELAYEDEXPANSION
SET "LINECOUNT="
ECHO ConsoleWidth: %ConsoleWidth% characters
tested on Windows XP and Windows 7, both in Czech language
Powershell's (Get-Host).UI.RawUI.WindowSize property sets or returns the dimensions of the current console window. You can capture it with a for loop thusly:
for /f %%I in ('powershell ^(Get-Host^).UI.RawUI.WindowSize.width') do set width=%%I
Alright, here's one that doesn't require powershell to be installed. It composes, runs and deletes a .Net application to set a batch script variable. :)
#echo off
setlocal
pushd "%windir%\microsoft.net\"
for /f "delims=" %%I in ('dir /s /b csc.exe') do (
set csc=%%I
goto next
)
:next
popd
echo using System;>width.cs
echo class Width {>>width.cs
echo public static void Main() {>>width.cs
echo string m1 = "{0}";>>width.cs
echo Console.WriteLine^(m1, Console.WindowWidth^); } }>>width.cs
"%csc%" /out:width.exe width.cs >NUL 2>NUL
for /f %%I in ('width.exe') do set width=%%I
del width.exe width.cs
echo %width%
You can't get it in an environment variable, but it is stored in the registry so you can access it from your batch script.
There are answers here about how to change it:
How to change Screen buffer size in Windows Command Prompt from batch script
In a similar way you can use reg.exe QUERY [key details] rather than reg.exe ADD [details]. See the Technet documentation for HKCU\Console for details.
For a one simple line:
for /f tokens^=2 %%w in ('mode con^|find "Col"')do set _width=%%~w"
Related
This question already has answers here:
Assign output of a program to a variable using a MS batch file
(12 answers)
How to set commands output as a variable in a batch file [duplicate]
(9 answers)
Closed 9 months ago.
I'm looking to get the result of a command as a variable in a Windows batch script (see how to get the result of a command in bash for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome.
The humble for command has accumulated some interesting capabilities over the years:
D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008
Note that "delims=" overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.
To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):
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%
To capture a piped expression, use ^|:
FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"
If you have to capture all the command output you can use a batch like this:
#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
All output lines are stored in VAR separated with "!".
But if only a single-line console-output is expected, try:
#ECHO off
#SET MY_VAR=
FOR /F %%I IN ('npm prefix') DO #SET "MY_VAR=%%I"
#REM Do something with MY_VAR variable...
#John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)
To get the current directory, you can use this:
CD > tmpFile
SET /p myvar= < tmpFile
DEL tmpFile
echo test: %myvar%
It's using a temp-file though, so it's not the most pretty, but it certainly works! 'CD' puts the current directory in 'tmpFile', 'SET' loads the content of tmpFile.
Here is a solution for multiple lines with "array's":
#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
But you might want to consider moving to another more powerful shell or create an application for this stuff. It's stretching the possibilities of the batch files quite a bit.
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
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
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%"
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.
I am trying to check OS version from a batch file and I am running into the following problem.
The line
FOR /F "tokens=*" %%i IN ('ver') DO (SET var=%%i)
will freeze the cmd when executing from a batch file while the command ver by itself (in the same batch file) executes without problem. (ver has the following output.)
Microsoft Windows [Version 10.0.18362.356]
What could be wrong in the expression?
To avoid recursion and unexcpected FOR/F behaviour, you can use a guard in the AutoRun batch script (like the variable based one shown by #sst).
#echo off
setlocal EnableDelayedExpansion
set "cmd=!cmdcmdline!"
if "!cmd!" == "!cmd:/=!" (
REM *** Define doskey macros
2>nul (
doskey npp="%ProgramFiles(x86)%\notepad++\notepad++.exe" $*
)
endlocal
REM *** Set additional variables
REM *** Change to a default directory
cd c:\temp
)
As it is mentioned in the comments beneath your question, the apparent freezing is caused by fact that you've setup that cmd statement to be executed through the cmd's AutoRun registry setting: [HKEY_LOCAL_MACHINE/HKEY_CURRENT_USER]\Software\Microsoft\Command Processor\AutoRun
When using for /F to capture the output of another command/program, an implicit instance of cmd will be invoked to execute the command/program referenced in the for's IN clause.
When there is an entry in the cmd's AutoRun registry setting that implicit cmd instance will in turn execute the AutoRun commands, And in your case that AutoRun command will execute another instance of cmd through the for /F command. You see that where it is going: infinite chain of nested cmds will be launched until it exhaust system resources.
To avoid trapping in the infinite loop, you need to guard the statement from executing more than once
Here is one method which is written as a batch file:
:: This batch file can be safely executed through cmd's Autorun
#echo off
if not defined WinVer (
set "WinVer=AutorunGuard"
for /F "tokens=1* delims=[" %%A in ('ver') do (
for /F "tokens=2 delims=] " %%V in ("%%B") do set "WinVer=%%V"
)
)
I've also extended the method of extracting windows version to include only the version number, not the whole version string which is return by ver
It can be used to extract version number for windows versions from Windows 2000 to Windows 10
If you don't want to use a batch file, and prefer to put the statement strait in to AutoRun registry setting, this one-liner can be used instead:
#if not defined WinVer set "WinVer=AutorunGuard" & for /F "tokens=1* delims=[" %A in ('ver') do #for /F "tokens=2 delims=] " %V in ("%B") do #set "WinVer=%V"
Don't name your batch file as ver.bat;
Rename it for example as CMD_Version.bat
#echo off
FOR /F "tokens=*" %%i IN ('ver') DO (SET var=%%i)
echo %var%
pause
You could get the information from Win32_OperatingSystem using wmic:
#For /F "EOL=V" %%A In ('WMIC OS Get Version')Do #For /F "Tokens=*" %%B In ("%%A")Do #Set "var=%%B"
or powershell:
#For /F %%A In ('"PowerShell (GWMI Win32_OperatingSystem).Version"')Do #Set "var=%%A"
You could also do the same using wsh, i.e. leveraging one of the vbscript or jscript engines.
An alternative, though not as robust as using WMI, is to get the information from the registry.
#Echo Off
Set "RKey=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Set "KVal=\<CurrentBuildNumber\> \<CurrentVersion\> \<ProductName\> \<UBR\>"
For /F Tokens^=1-2* %%A In (
'^""%__AppDir__%reg.exe" Query "%RKey%" 2^>NUL^|"%__AppDir__%findStr.exe" /I "%KVal%"^"'
)Do #If "%%A"=="UBR" (Set /A %%A=%%C)Else Set "%%A=%%C"
Echo(%ProductName% %CurrentVersion%.%CurrentBuildNumber%.%UBR%
Pause
Note: I do not think that UBR is a pre Windows 7 entry, so in those cases you'd simply have a trailing period in your output.
How to make a character line across the width of the command line Windows?
In Linux, I can do like this
printf '\n%*s\n\n' \"${COLUMNS:-$(tput cols)}\" '' | tr ' ' -
In Windows, I have so far only
echo -----------------------
you can get the current width of your window with the mode command.
#echo off
setlocal enabledelayedexpansion
"set width="
for /f "tokens=2 delims=:" %%a in ('mode con^|more +4') do if not defined width set /a width=%%a
for /l %%a in (1,1,%width%) do set "line=!line!-"
echo %line%
If you are on a supported version of Windows, this can easily be done using PowerShell. PowerShell also runs on Linux/*NIX and Mac.
powershell -NoLogo -NoProfile -Command "'-' * $Host.UI.RawUI.WindowSize.Width"
I only know a workaround for it by determining the width of the command line window and repeating the character ofter enough.
Since I don't know if you only want it in the command prompt oder in a batch file I post what I made while ago for me. It only works in a batch file or when you save the second part in a batch file and call it in a command prompt window.
:RepeatChar <Char> <Count> <Variable>
setlocal enabledelayedexpansion
set tempRepChar=
for /L %%l in (1,1,%~2) do (
set tempRepChar=!tempRepChar!%~1
)
if /i "%~3"=="" (
echo %tempRepChar%
) else (
set %~3=%tempRepChar%
set tempRepChar=
)
goto :EOF
exit /b
(the extra exit /b in the RepeatChar function isn't really necessary, but I just do it for myself)
You can then call it within a batch file with
for /f %%f in ('powershell.exe -command $host.UI.RawUI.WindowSize.Width') do set WindowsWidth=%%f
call :RepeatChar "-" %WindowsWidth% Stipline
echo %Stripline%
exit /b
if you don't give it the 3rd parameter then it just echos the line so if you only need it once you can just use
call :RepeatChar "-" %WindowsWidth%
Or you can also store or use it via a for loop, like
for /f %%f in ('powershell.exe -command $host.UI.RawUI.WindowSize.Width') do set WindowsWidth=%f
for /f %%f in ('call temp.bat "-" "%WindowsWidth%"') do (
echo %%f
set Stripline=%%f
)
I have a batch file which has the content
FOR /F "tokens=1-4" %%A in ("REG QUERY HKCU\Environment\") DO (
echo %%A %%B
)
pause
However when I run this, a cmd window opens like I expect but it closes very fast, before I can read the text. What can I do to prevent this, and why is it happening.
Doesn't happen on my machine too, you can also try to run from command line:
cmd /K your_file.bat
This works for me :
#echo off
FOR /F "tokens=1*" %%A in ('REG QUERY HKCU\Environment\') DO (
echo "%%A" "%%B"
)
pause
Independtly of what the code does (as indicated by Hackoo, probably the inner double quotes should be single quotes), looking at the observed behaviour it seems there is a problem with cmd extensions. The default configuration is usually extensions enabled, but if extensions are disabled the for /f is not recognized as a valid command and batch execution is ended.
Try with
setlocal enableextensions
FOR /F "tokens=1-4" %%A in ('REG QUERY HKCU\Environment\') DO (
echo %%A %%B %%C %%D
)
pause
This question already has answers here:
Assign output of a program to a variable using a MS batch file
(12 answers)
How to set commands output as a variable in a batch file [duplicate]
(9 answers)
Closed 9 months ago.
I'm looking to get the result of a command as a variable in a Windows batch script (see how to get the result of a command in bash for the bash scripting equivalent). A solution that will work in a .bat file is preferred, but other common windows scripting solutions are also welcome.
The humble for command has accumulated some interesting capabilities over the years:
D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%i
D:\> echo %today%
Sat 20/09/2008
Note that "delims=" overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.
To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):
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%
To capture a piped expression, use ^|:
FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"
If you have to capture all the command output you can use a batch like this:
#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
All output lines are stored in VAR separated with "!".
But if only a single-line console-output is expected, try:
#ECHO off
#SET MY_VAR=
FOR /F %%I IN ('npm prefix') DO #SET "MY_VAR=%%I"
#REM Do something with MY_VAR variable...
#John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)
To get the current directory, you can use this:
CD > tmpFile
SET /p myvar= < tmpFile
DEL tmpFile
echo test: %myvar%
It's using a temp-file though, so it's not the most pretty, but it certainly works! 'CD' puts the current directory in 'tmpFile', 'SET' loads the content of tmpFile.
Here is a solution for multiple lines with "array's":
#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
But you might want to consider moving to another more powerful shell or create an application for this stuff. It's stretching the possibilities of the batch files quite a bit.
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
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
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%"
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.