Reputation: 307
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
Upvotes: 1
Views: 840
Reputation: 58931
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
Upvotes: 3