views:

237

answers:

1

Hi,

I want to use bat to automate some of my work. It should first look up the value of a certain registry key, and then copy some files to the directory that included in the registry key value. I used reg query command to look up registry, such as:

REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROCESSOR_ARCHITECTURE

The result seems contains carriage return and I need to remove it, I've tried some solutions but all failed. Could anyone help me?

+3  A: 

For that particular case, you can start with:

for /f "tokens=3" %i in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROCESSOR_ARCHITECTURE ^| findstr PROCESSOR_ARCHITECTURE') do set x=%i

which will set %x% to x86 (in my case).

If the third value on the line can contain spaces, you'll need to get a bit trickier


The following script shows one way to be trickier. It basically uses a debug line to produce fictional output from reg that gives you an architecture with spaces.

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=2*" %%a in ('echo.    PROCESSOR_ARCHITECTURE      REG_SZ  x86 64-bit     grunter') do (
    set arch=%%b
)
echo !arch!
endlocal

The output of that is:

x86 64-bit grunter

as expected (keep in mind it collapses multiple spaces into one). The tokens=2* bit puts token 2 (REG_SZ) into %%a and all following tokens into %%b.

So a good final script would be:

@setlocal enableextensions enabledelayedexpansion
@echo off
set id=HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
set key=PROCESSOR_ARCHITECTURE
for /f "tokens=2*" %%a in ('REG QUERY "!id!" /v !key! ^| findstr !key!') do (
    set arch=%%b
)
echo !arch!
if !arch!==x86 echo arch was x86
endlocal

This script outputs:

x86
arch was x86

so you know it's being set as you desire.

paxdiablo
+1 Thats what I would come up with. If the value contains spaces, you can use `for /f "tokens=2*" ...`. This site gives some explanations: http://www.robvanderwoude.com/ntregistry.php
Frank Bollack
@Pax, I've tried your solution. I redirect the result to a txt file:echo %x% > 1.txtIt still contains a carriage return. It also return false for this statement: if %x%=="x86"
eric2323223
Very helpful! Thanks, Frank.
eric2323223
@eric, echo will add its own line end which is why it's showing up in the file. The reason why your `if` fails is because of the quotes - they should either be around _both_ sides of the `==` or neither side. If you have a look at the updated script at the bottom of my answer, you'll see what I mean - it sets `arch` correctly to `x86`, assuming you architecture _is_ actually x86 of course.
paxdiablo
@Pax, you are right, thanks.
eric2323223