Home > OS >  The for command of batch cannot return the value
The for command of batch cannot return the value

Time:07-21

I want to execute some commands and download things with batch

There are multiple servers and I want to load balance it. There is also the reason for the network. So I want to test with tcping

There is a problem now that the return value of the for execution command cannot be obtained The tcping tool I use: https://github.com/cloverstd/tcping

code:

for /F %%a in (‘powershell ./tcping.exe -H https://a.server…’) do @set server1=%%a
echo “%server1%”

The content returned after execution: Minimum

Expected return: Minimum = 100.0000ms, Maximum = 100.000ms, Average = 100.0000ms

The value of for can only get the first one (Minimum ) Not all content returned because there is a space. The test is the same for other commands, and it will be terminated when a space is encountered.

So there is no way to get the latter value

I read Microsoft's doc, and command help, which doesn't mention more about what set returns for command

Is there any solution?


Also, I'm new to programming and it's not that long. Also not very good at using this community. If there is something wrong, please forgive me

CodePudding user response:

Couple things:

  1. I would not use a batch command unless I absolutely had to. PowerShell is much easier to use than the cryptic nonsense created over 20 years ago.
  2. You could create a PowerShell .ps1 script and do the whole operation in native PowerShell and make it much easier on yourself.

If you are going to use PowerShell, try using Test-Connection instead of a command line app. It will provide you plenty of information you can base your logic on to make the operation more resilient.

CodePudding user response:

  • To make for /f report lines in full in a single variable instead of splitting them by whitespace and reporting each token in a separate variable, use "delims="

    • Run for /? for a full description of the for statement (this produces paged output, requiring a keypress to move to the next page).
  • As Stephan points out in a comment, you do not need PowerShell to call an external program such as tcping.exe - just call it directly, which also makes the invocation much faster.

Therefore, use the command Aacini suggests in a comment:

for /f "delims=" %%a in ('tcping.exe -H https://a.server…') do @set server1=%%a

Unless you're forced to use batch files and direct use of PowerShell isn't an option:

  • Consider implementing the functionality in a PowerShell script (.ps1) as proposed in Jim's answer.

  • For more information on the trade-offs between using pure batch-file solutions, hybrid batch-file solutions (batch files that call powershell.exe) and pure PowerShell solutions (.ps1 files), see this answer.

  • Related