JSI Tip 7723. How can I prevent the FOR command from stripping leading spaces?

When you use the FOR command to parse the contents of a file, or the output of a command, leading spaces in the first object are stripped. For example:

set query=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=*))" -attr department manager sAMAccountName -limit 0
for /f "Tokens=*" %%a in ('%query%') do @echo %%a

might return:

department    manager                                         sAMAccountName
Administrator
Testing       CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=ORG    USER_OU_TEST


where the department (and department / manager) values are stripped when these attributes are nul (or contain spaces).
If you wish to prevent this behavior, redirect the object through a Findstr command, as follows:
set query=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=*))" -attr department manager sAMAccountName -limit 0
for /f "Tokens=1* Delims=:" %%a in ('%query% ^|Findstr /l /n /v /c:"*$"') do @echo %%b

NOTE: The *$ string in the search argument is any string that will never be found in the object.

returning:

  department    manager                                         sAMAccountName
                                                                Administrator
  Testing       CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=ORG    USER_OU_TEST
Notice that the two (2) leading spaces on the heading and the fully populated data line are NOT stripped, and that the missing department and manager attribute values do NOT get stripped.



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish