reading variables value from text file in batch script - windows

In my BAT file, i want to read these data from .txt file and need to set each data into one variable
SQLUserName=MFiles
WrapperSQLServerName=usa.com
WrapperDatabase=Wrapper
WrapperAssemblyLocation=D:\Assembly
MFilesNetworkAddress=USA-S1
MFilesVaultName=MF2
MFilesUsername=User
MFilesPassword=
MFilesVaultGUID={26F30-E120-408C-8035-04D85D6}
MFilesWebServerURL=www.WebServer.com
SQLMailProfileName=NoReply
WrapperSupportEmail=thejus#WebServer.com
I tried with this code
FOR /F "tokens=2 delims==" %%a IN ('find "WrapperSupportEmail" ^<config.txt') DO SET SupportEmail=%%a
But it throws error
find is not recognized as an internal or external command operable program or batch file
Please help me
Thejus T V

If the schema of your input file is fixed (keyword=value) and you want to assign all values to an environment variabel named keyword it is very, very easy. try this:
for /f "tokens=1,2 delims==" %i in (config.txt) do set %i=%j
remember to change %i and %j to %%i and %%j if you want to put this call into a cmd-file.

when two members with high reputation tell you it works, then it shouldn't be the worst of all ideas to at least try it.
rem #echo off
for /f "delims=" %%i in (config.txt) do set _%%i
pause
set _
I REMd the #echo off, so you can watch, how every single line get's processed.
(Your original error find is not recognized ... is probably because you messed up your %path%-variable, but you don't need find for this task.)

My code is correct one only. Only issue is windows cant locate find.exe. I included the .exe on same location and after that everything works fine.
Its working fine in Win 7 and Win 10 without adding Find.exe

Related

capture result of wmic command to variable [duplicate]

This question already has answers here:
Set the value of a variable with the result of a command in a Windows batch file [duplicate]
(6 answers)
Assign command output to variable in batch file [duplicate]
(5 answers)
Closed 3 years ago.
I am trying to write a small batch script to install an app from a thumb drive. The problem is the drive letter changes when plugged into different machines depending on the available drive letters. I have the script to run the installation but would like to add a script to the beginning that would detect the assigned drive letter of my inserted thumb drive and store it in a variable that I could then substitute in the rest of the script for the drive letter to complete the installation.
I got the command to identify the assigned drive letter of the thumb drive which works on its own.
wmic logicaldisk where volumename="StacelandFlash" get name
Result: D: (correct)
But I can't seem to assign it to a variable.
set X=wmic logicaldisk where volumename="StacelandFlash" get name
echo X
Result: X
set X=wmic logicaldisk where volumename="StacelandFlash" get name
echo %X%
Result: wmic logicaldisk where volumename="StacelandFlash" get name
Firstly, to capture the output of a command to a variable use for /F. See for /? in a cmd console for full details. Example:
for /f "tokens=2 delims=:" %%I in ('find /c /v "" "notes.txt"') do (
set /a "linecount=%%I"
)
rem // %linecount% now contains the number of lines in notes.txt
Now, there are a couple of complications unique to capturing WMI query results. Firstly, your wmic command includes an equals sign, which will break a for /f. That part's easy enough to fix: either escape the = with a caret (e.g. ^=), or just surround the equation in quotation marks.
The next hurdle is a bit trickier. WMI results are encoded in a non-ANSI encoding (UCS-2 LE). Capturing the output of wmic also captures the output's encoding, resulting in the last character being moved to the beginning of the line or other unexpected behavior. The workaround for that is to use a second nested for /f to sanitize the value.
With all that in mind, I think this is what you're looking for:
#echo off
setlocal
for /f "tokens=2 delims==" %%I in (
'wmic logicaldisk where "volumename='StacelandFlash'" get name /value'
) do for /f "delims=" %%# in ("%%I") do set "driveletter=%%~#"
echo %driveletter%
Note: credit #Dave Benham for discovering this workaround.
You need to run the command within a For Loop.
#Echo Off
For /F "Skip=1 Delims=" %%A In ('
"WMIC LogicalDisk Where (VolumeName='StacelandFlash') Get Name"
') Do For %%B In (%%A) Do Set "USB=%%B"
Echo(%USB%
Timeout -1
I suppose the batch file executed is stored on the thumb drive. And this batch file is executed with a double click. Therefore all you need is:
set "DriveLetter=%~d0"
%~d0 references the drive of argument 0 which is the batch file name. Run in a command prompt window call /? for details on how to reference arguments of a batch file. %~d0 expands to D:, E:, ...

different behaviors of WMIC in command line and windows explorer

My conundrum is related to the q/a thread at the following link: How to append date to directory path in xcopy
I'm new to this forum, and I had the same kind of question, and I'm using Windows 10, so I used the answer given in that thread by foxidrive about how to use WMIC for this, and it works fabulously, except for one issue that I've not yet figured out...
I modified the script that foxidrive provided, as follows:
#echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
set YYYY=%dt:~0,2%
set YY=%dt:~2,2%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
for /f "tokens=%dow%" %%a in ("Su Mo Tu We Th Fr Sa") do set day=%%a
set stamp=%YY%%MM%%DD%%HH%%Min%%day%
REM echo Today is %day%.
md "%stamp%MoreDirName"
xcopy %source% /E /y .\"%stamp%MoreDirName"
When I run the batch file from cmd.exe, I get the desired result, namely, a directory is created with the date format the way I want it, and the date and time stamp that I want includes the name of the day of the week. However, when I double-click on the batch file in windows explorer, the folder is created and folders/files are copied, but the name of the day of the week does not appear in the new folder name. I am confused by this behavior and I would like to know how to override it, please.
I would have researched the issue more, but I am not sure what to search for other than ``different behaviors of WMIC in command line and windows'', and such a search yielded no helpful results. But since my efforts were based specifically upon the referenced stack exchange q/a thread, it seems to me that this is an appropriate place to document this strange behavior and get explanations if possible, which might help me, and others later, to compose better script.
I am confused by this behavior and I would like to know how to override it
There is no problem with wmic. The Issue is with your batch file, which contains two undefined variables).
for /f "tokens=%dow%" %%a in ("Su Mo Tu We Th Fr Sa") do set day=%%a
You don't set dow anywhere in your batch file.
xcopy %source% /E /y .\"%stamp%MoreDirName"
You also don't set source anywhere in your batch file.
What probably happened:
You have dow and source hanging about in your cmd environment from another batch file you have run that does not include the setlocal command (which prevents variables leaking into the parent cmd shell).
That means:
The batch file run from a cmd shell will work if dow and source are set in that instance of cmd.
The batch run from explorer won't work because it start a new instance of the cmd shell and dow and source are undefined.
Corrected batch file:
Here is a modified version of your batch file that will work when run from a cmd shell or from explorer, and correctly sets up Day of the Week.
rem #echo off
setlocal
set source=SomeSourceValue
rem use findstr to strip blank lines from wmic output
for /f "usebackq skip=1 tokens=1-6" %%g in (`wmic Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year ^| findstr /r /v "^$"`) do (
set _day=00%%g
set _hours=00%%h
set _minutes=00%%i
set _month=00%%j
set _seconds=00%%k
set _year=%%l
)
rem pad with leading zeros
set _month=%_month:~-2%
set _day=%_day:~-2%
set _hh=%_hours:~-2%
set _mm=%_minutes:~-2%
set _ss=%_seconds:~-2%
rem get day of the week
for /f %%k in ('powershell ^(get-date^).DayOfWeek') do (
set _dow=%%k
)
set _stamp=%_year%%_month%%_day%%_hh%%_mm%%_dow:~0,2%
md "%_stamp%MoreDirName"
xcopy %source% /E /y .\"%_stamp%MoreDirName"
endlocal
Notes:
The batch file uses a more elegant way to retrieve the timestamp components from wmic.
Modify the above as appropriate to set source correctly.
Credits:
Thanks to Danny Beckett for this answer which provided the PowerShell weekday trick.
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
for /f - Loop command against the results of another command.
getdate - Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).
setlocal - Set options to control the visibility of environment variables in a batch file.
variables - Extract part of a variable (substring).
wmic - Windows Management Instrumentation Command.

String replacement within FOR /F into batch file

There are a handful of questions on SO that look similar, but I cannot figure out some behaviour and I am looking for help.
Below is a snippet from a batch file I am trying to write which will load in a set of directories and potentially replace letter substitutions with an expanded path, e.g. the properties file might look like:
location1=C:\Test
location2=[m]\Test
Where location1 points to C:\Test and location2 points to C:\Program Files(x86)\MODULE\Test, because [m] is a shorthand to C:\Program Files(x86)\MODULE.
The batch script, to this point, is simply trying to read in the list of file paths and expand/replace the [m].
SET build.dir=%~dp0%
SET progfiles=%PROGRAMFILES(X86)%
IF "%progfiles%"=="" SET progfiles=%ProgramFiles%
SET local.properties=%build.dir%local.properties
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=1* delims==" %%i IN (%local.properties%) DO (
SET local.dir=%%j
SET local.dir=!local.dir:[m]=%progfiles%\MODULE!
echo !local.dir!
)
ENDLOCAL
Running this kicks out an error:
\MODULE was unexpected at this time.
If I replace the FOR with the following instead:
set test="[m]\Proj\Dir"
set test=!test:[m]=%progfiles%\MODULE!
echo %test%
I get the desired C:\Program Files(x86)\MODULE\Proj\Dir printed out...so I'm confused why it works fine outside of the FOR loop.
My understanding about delayed expansion is that it 'expands' at runtime...which you get to happen using !! instead of %% wrapped around the variable. Furthermore, as I'm creating the local.dir variable inside the FOR loop scope, I must use delayed expansion in order to access it with the updated value for the iteration.
I feel like the problem is using %progfiles%, like there's some special syntax I need to use in order to make it work but nothing is adding up for me. When I echo %progfiles%, it prints out as C:\Program Files(x86 -- note the missing trailing ).
Any ideas? Thanks
Tested suggestion:
D:\Projects\Test\Build>test
*** "D:\Projects\Test\Build\local.properties"
*** "","C:\Program Files (x86)"
[m]=C:\Program Files (x86)\MODULE
Adding quotes around the whole expression makes it work -- can't use other characters for some reason (like []) -- and since I want to append to the path later, we can safely remove the quotes afterwards:
SET local.dir="!local.dir:[m]=%progfiles%\MODULE!"
SET local.dir=!local.dir:"=!
Test this to see if you can nut out the issue:
The double quotes are to provide robust handling in a system with long file/path names.
The () are unquoted which are a problem in a batch script, when inside a loop.
#echo off
SET "build.dir=%~dp0%"
SET "progfiles=%PROGRAMFILES(X86)%"
IF "%progfiles%"=="" "SET progfiles=%ProgramFiles%"
SET "local.properties=%build.dir%local.properties"
echo *** "%local.properties%"
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq tokens=1* delims==" %%i IN ("%local.properties%") DO (
SET "local.dir=%%j"
echo *** "!local.dir!","%progfiles%"
SET "local.dir=!local.dir:[m]=%progfiles%\MODULE!"
echo !local.dir!
)
ENDLOCAL
pause
It has to do with the () characters that end up in your progfiles string. If you take them out, the substitution seems to work fine.
My suggestion is to ditch command for this particular purpose and use one of the other standard tools that Windows comes with. While my personal preference would be Powershell (since it's so much more powerful and expressive), you may just need something quick that you can integrate into existing cmd.exe stuff.
In that case, try the following VBScript file, xlat.vbs:
set arg = wscript.arguments
wscript.echo Replace(arg(0),arg(1),arg(2))
Your batch file then becomes something like, noting the inner for /f which captures the output of the VBS script and assigns it to the variable:
#echo off
SET build.dir=%~dp0%
set progfiles=%PROGRAMFILES(X86)%
if "%progfiles%"=="" set progfiles=%ProgramFiles%
set local.properties=%build.dir%local.properties
setlocal enabledelayedexpansion
for /f "tokens=1* delims==" %%i in (%local.properties%) do (
set local.dir=%%j
for /f "delims=" %%x in ('cscript.exe //nologo xlat.vbs "!local.dir!" "[m]" "%progfiles%\MODULE"') do set local.dir=%%x
echo !local.dir!
)
endlocal
Running that, I get the output:
C:\Test
C:\Program Files (x86)\MODULE\Test
which I think is what you were after.

Get file name and append to beginning of line

I'm trying to get a side-by-side file path and file name in a text file so I can make inserting into a database easier. I've taken a look at other examples around SO, but I haven't been able to understand what is going on. For instance, I saw this batch file to append file names to end of lines but figured that I shouldn't ask for clarification because it's 1.5 years old.
What I have is a text file of file paths. They look like this:
\\proe\igi_files\TIFFS\AD\1_SIZE_AD\1AD0019.tif
What I want it to look like is this:
1AD0019.tif \\proe\igi_files\TIFFS\AD\1_SIZE_AD\1AD0019.tif
so that I can insert it into a database. Is there an easy way to do this on Windows via Batch files?
No batch file required. From the command line:
>"outputFile.txt" (for /f "usebackq eol=: delims=" %F in ("inputFile.txt") do #echo %~nxF %~dpF)
But that output format is risky because file and folder names can contain spaces, so it may be difficult to determine where the file name ends and the path begins. Better to enclose the file and path within quotes.
>"outputFile.txt" (for /f "usebackq eol=: delims=" %F in ("inputFile.txt") do echo "%~nxF" "%~dpF")
if done within a batch file, then percents must be doubled.
#echo off
>"outputFile.txt" (
for /f "usebackq eol=: delims=" %%F in ("inputFile.txt") do echo "%%~nxF" "%%~dpF"
)
You should read the built in help for the FOR command. Type help for or for /? from a command prompt to get help. That strategy works for pretty much for all commands.
In powershell, this little script should do the trick. In the first line, just specify the name of the text file that contains all the file paths.
$filelist="c:\temp\filelist.txt"
foreach($L in Get-Content $filelist) {
$i = $L.length - $L.lastindexof('\') -1
$fname=$L.substring($L.length - $i, $i)
echo ($fname + ' ' + $L)
}
If you don't have powershell installed on your machine, check out http://technet.microsoft.com/en-us/library/hh847837.aspx.
#ECHO OFF
SETLOCAL
(
FOR /f "delims=" %%i IN (yourfile.txt) DO ECHO %%~nxi %%i
)>newfile.txt
GOTO :EOF
No big drama - all on one active line, but spaced for clarity

Batch file for loop statement

I've put together the batch file below; I don't have much experience with batch files and I can't figure out why the file fails with an error message stating that the:
DO command was unexpected.
Looking at the following code, does anyone know what I did wrong? Thanks.
#ECHO OFF
REM Set arguments supplied by Subversion
SET REPOS = %1
SET REV = %2
REM Set working directory path
SET WORKSPACE = D:\apache\htdocs
REM Assign changes to variable
SET CHANGES = svnlook changed %REPOS% -r %REV%
REM Update only changed files
FOR /f %%a IN %CHANGES% DO svn update %%a
FOR /f %%a IN %CHANGES% DO svn update %%a
should be
FOR /f %%a IN (%CHANGES%) DO svn update %%a
Hope this helps,
I'm guessing that %CHANGES% is not in the correct format/structure for the loop so the DO cannot be executed. Add the following line before the loop to check you're getting what you expected from the SET CHANGES command;
ECHO %CHANGES%
If the assignment is more batch code to execute you might need to use CALL. What are you passing in when calling the batch file for %1 and %2?
can you try to run it without the REM Statement. Comments sometimes make things work differently.
After modifying my original code I've got it to 'work.'
The svnlook command returns for example: trunk\images\smileyface.jpg
Currently, the for loop returns only the 'U' rather than the 'smileyface.jpg' which I want. So, while the code now works, it does function yet how I'd like (still working on it).
Below is the revamped code (Note: I had to remove all spaces between my variables and their assigned values).
#ECHO OFF
REM Set arguments supplied by Subversion
SET REPOS=%1
SET REV=%2
REM Set working directory path
SET WORKSPACE=D:\apache\htdocs
REM Assign changes to variable
SET CHANGES=svnlook changed %REPOS% -r %REV%
REM Update only changed files
FOR /F "usebackq" %%a IN (`%CHANGES%`) DO (svn update %%a)

Resources