Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are correct that a FOR /L loop "always" counts to completion. (Well, actually there are some drastic coding methods that can break it, but no need to go there)</p> <p>However, even though the loop counts to completion, the DO clause is skipped once the GOTO FOUND statement has been executed. You can prove this to yourself by inserting <code>echo testing %%a&amp;</code> in the front of your existing DO clause. You will see that no additional testing takes place once you have found your free port.</p> <p>The FOR /L loop counts very fast (at least by batch standards), so I wouldn't worry about the extra counting. Now if your were counting 1 through 1 million, then I <em>might</em> worry. At 10 million I am definitely concerned.</p> <p>I can simplify your existing logic a bit. You can combine the 2 FIND statements into a single FINDSTR using a regular expression.</p> <pre><code>for /L %%a in (8000,1,8100) do netstat /a /n | findstr /rc:"%%a.*LISTENING" || set tmp_freeport=%%a &amp;&amp; goto found </code></pre> <p>I am no expert concerning IP addresses and ports, but I am concerned that your FIND logic may be inadequate to screen for used ports. I think looking for a colon before and a space after the port will make it more reliable. Also, I doubt you want to see the text of the used ports, so I redirected the FINDSTR output to nul.</p> <pre><code>for /L %%a in (8000,1,8100) do netstat /a /n | findstr /rc:":%%a .*LISTENING" &gt;nul || set tmp_freeport=%%a &amp;&amp; goto found </code></pre> <p><em><strong>Note:</em></strong> GOTO :Label will immediately terminate all other forms of a FOR loop. Only the FOR /L variant continues to count after a GOTO.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload