Reputation: 59
I have a batch script that creates a file called "output.txt" and writes some system information. I want to open that file and store that information in a variable. however, when I run the script it gives me the "system cannot find the file output.txt". This is the same script that writes the file as well.
@echo off
(wmic os get Caption)>>output.txt
for /F "tokens=2* skip=1" %%G in (output.txt) do set info=%%G
echo version:%info%
pause
(wmic os get Caption)>>output.txt
works becuase It creates a file with the following lines:
Caption
Microsoft Windows 10 Home
I'm simply trying to get the windows operating system name and store it in a variable for example
info=Windows 10 Home
Upvotes: 0
Views: 629
Reputation: 38623
I would probably do it without creating an intermediate file to read then delete:
@For /F Tokens^=6Delims^=^" %%A In ('WMIc OS Get Caption /Format:MOF 2^>Nul')Do @Set "info=%%A"
You should have the value stored, (without any unnecessary trailing characters), to the variable %info%
for the duration of the cmd.exe
session, as long as you don't modifiy/overwrite it.
Echo Version:%info%
Please note that there is a bug in Windows 7, (I think), which may prevent the mof.xsl
file from being picked up by WMIC.exe
. There are both temporary and more permanent fixes or workarounds for that though, which are really outside of the scope of your question.
[Edit /]
I thought I'd include this registry based batch-file as a quicker to retrieve alternative solution:
@For /F "EOL=HTokens=2*" %%A In (
'Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /V ProductName 2^>Nul'
)Do @Set "info=%%B"
Upvotes: 1
Reputation: 101656
You are not using a full path so output.txt can end up anywhere. Your example does work on my machine so maybe your real code is a little bit different?
Since you are already using for /F
you might as well just parse the command directly without a temporary file:
FOR /F "tokens=1,* delims==" %%A IN ('wmic os get Caption /value^|find "="') DO @set info=%%B
echo.info=%info%
Upvotes: 1