问题
I'm trying to get a Computer System Model type via Batch file. for this i've created this script:
systeminfo | find "System Model" > %temp%\TEMPSYSINFO.txt
for /F "tokens=2 delims=:" %%a in (%temp%\TEMPSYSINFO.txt) do set SYSMODEL=%%a
del %temp%\TEMPSYSINFO.txt
set SYSMODEL=%SYSMODEL:~1%
echo %SYSMODEL% >%temp%\SYSMODEL.txt
del %temp%\SYSMODEL.txt
set "Line1=*** System Model: %SYSMODEL%"
echo %Line1%
but when I run it i get extra spaces:
*** System Model: OptiPlex 9010
Any idea how can I fix it?
回答1:
You're doing it the hard way. Use wmic
. It's a lot faster and less complicated to scrape.
for /f "tokens=2 delims==" %%I in ('wmic computersystem get model /format:list') do set "SYSMODEL=%%I"
set "Line1=*** System Model: %SYSMODEL%"
echo %Line1%
wmic
lets you query all sorts of neat wmi garbage. wmic /?
for more info.
(updated per OP's comment under Fuzzy Button's answer)
回答2:
You could use
for /F "tokens=2* delims=: " %%a in (%temp%\TEMPSYSINFO.txt) do set SYSMODEL=%%b
meaning use delimiters COLON or SPACE, making the text token3 BUT as the text might? include colon or space, the *
means 'the rest of the line following the delimiters after token 2
the first-mentioned token (2) is the one that gets assigned to
%%a, the next highest (*) to
%%b`
Now you could also code
for /F "tokens=2* delims=: " %%a in (
'systeminfo 2^>nul ^| find "System Model" '
) do set SYSMODEL=%%b
which means you don't need the TEMPSYSINFO.txt file. This executes the single-quoted command line - the special characters >
and |
need a caret (^
) to 'escape' them (turn off their special meaning) as far as the FOR is concerned (they belong to the quoted command
, not the FOR.)
The 2>nul will suppress the SYSTEMINFO progress text.
And it's quite legitimate to break this line - just have to be careful precisely where you do it. Makes the code more readable.
回答3:
For what it's worth, I tried this and it replaced all double spaces to nothing,
with echo =%SYSMODEL%=
producing :=my sysmodel =
(just one trailing space) :)
set SYSMODEL=%SYSMODEL: =%
EDIT
So, using Peter's excellent suggestion to put the piped commands into the FOR /F
, which I tried that before but came unstuck with a plain |
instead of ^|
:)
for /F "tokens=2 delims=:" %%a in ('systeminfo 2^>nul ^| find "System Model"') do set SYSMODEL=%%a
set SYSMODEL=%SYSMODEL: =%
EDIT 2
rojo's answer is great, but it still leaves trailing space for me, so I ended up still using the %var: =%
trick
for /f "tokens=2 delims==" %%a in ('wmic computersystem get model /format:list') do set SYSMODEL=%%a
set SYSMODEL=%SYSMODEL: =%
echo =%SYSMODEL%=
来源:https://stackoverflow.com/questions/15973276/systeminfo-get-computer-system-model-via-cmd-extra-spaces-bug