Search code examples
batch-filedsquery

How to handle multiple 'for' statements in a batch file?


I am attempting to create a batch file which will take a list of users from a text file, run a dsquery against Active Directory to determine if the account has been disabled or not, and then output the results to a different text file containing the user ID and the status (yes/no) of whether they've been disabled or not.

I feel like I'm positioning the quotes or the parentheses incorrectly but I'm also not 100% sure if multiple 'for' statements can even be nested like this. Input much appreciated.

for /f "tokens=1" %%G in (termlist.txt) do (
for /f "Tokens=*" %%a in ('dsquery user -samid %%G^|dsget user -disabled^| Find /v "disabled"^| Find /v "dsget succeeded"') do set disable=%%a)
echo "%%G %disable%" >> termvalid.txt)

Solution

    1. You left out the space in front of each instance of the ^ character.
    2. Your entire FOR construct is loaded as one line (regardless of how many physical lines it occupies)... so %disable% is expanded at the time the entire construct is loaded and will not change at run time. You could enable delayed expansion, but there is no need for that in this case.

    Try this (use first line if you want to be sure you are not appending to an old unwanted file):

    if exist termvalid.txt del /f /q termvalid.txt
    for /f "tokens=1" %%G in (termlist.txt) do (
       for /f "Tokens=*" %%a in ('dsquery user -samid %%G ^|dsget user -disabled ^| Find /v "disabled" ^| Find /v "dsget succeeded"') do echo "%%G %%a" >> termvalid.txt))