SystemInfo - Get computer System Model via CMD - Extra spaces bug

后端 未结 3 1390
抹茶落季
抹茶落季 2021-01-29 01:17

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.t         


        
相关标签:
3条回答
  • 2021-01-29 01:23

    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)

    0 讨论(0)
  • 2021-01-29 01:23

    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%=
    
    0 讨论(0)
  • 2021-01-29 01:42

    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.

    0 讨论(0)
提交回复
热议问题