1

I am trying to run tracert command 2 times by using a do loop. I am doing this simply by counting the number of times "Trace complete." shows. So in the script below, I want the loop to run until the variable contains "Trace complete." 2 times. But obviously its not working.

do {
         $2+= tracert $ip 

   } until ( $2.Contains("Trace complete.") -ge 2) 

 #(  $2 | select-string "Trace complete").length -eq 2 

I also tried the select string method but both don't result in loop ending until Trace Complete has appeared twice. Any help please?

Edit 1:

I would also like to store the output of tracert in a variable so i can view it

1 Answer 1

3

The tracert command returns an array of strings thus the Contains() function will not work here.

Here is a solution where I increase the $count variable which is initialized with 0 by 1 every time the tracert command contains the string Trace complete by using a regex. if the joined string doesn't contain the term, I increase the variable by 0.

Finally, the until condition will stop when the $count variable is greater equal 2.

$count = 0
$output = do { 
    $output = tracert 127.0.0.1
    if (($output -join '' -match 'Trace complete\.')) {
        $output # outputs the tracert result
        $count++
    }

} until ( $count -ge 2) 

$output
Sign up to request clarification or add additional context in comments.

5 Comments

Hey, Thank you for your answer. Sorry i think I did not clarify what I was asking for but I also want to see the output of tracert. Can that be added to your script?
I changed the code. It now outputs your desired result.
Once the script is finished executing, it shows 2 results of tracert which is correct but when I check the $output variable, i only see the tracert results once instead of twice? Basically I am trying to run the tracert twice and mail the output.
I changed the code again. This time the output from the do loop gets captured and stored to the outer $output variable which you can reuse...
This is EXACTLY what i was looking for. Thank you so much!!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.