Maurice van Dorst
Maurice van Dorst

Reputation: 93

Handle 4 For loops at once?

Introduction to question

I'm trying to search for the following values: '02-08-1997' and '01-08-1997' in string $b1. To find that value, I used searching for the starting and ending index of the values around it.

How did I do it?

To do this I used 4 For loops, only to execute the exact same thing over and over again. I know this can be done much simpler; so far I haven't found a way to do so yet. I have to write multiple scripts like this, so I really need to find a simpler - more easy to read - way to do so.

These are 2 of the For loops I'm using:

$b1 = 'set-aduser -identity 3423-234-23-42-432 dorstm -replace @{ geboortedatum = 01-08-1997 } waarde_org = 02-08-1997'

For ($i = 0; $i -lt $b1InArray.Length; $i++) {
    if ($b1InArray[$i].contains("=")) {
        $e = $i
        break
    }
}


For ($j = ($e + 1); $j -lt $b1InArray.Length; $j++) {
    if ($b1InArray[$j].contains("}")) {
        $f = $j
        break
    }
}

Upvotes: 2

Views: 54

Answers (3)

Gert Jan Kraaijeveld
Gert Jan Kraaijeveld

Reputation: 1187

Many ways to do this. This could work for you:

(Select-String -InputObject $b1 -allmatches -Pattern '\d{2}-\d{2}-\d{4}').matches.value

it will output all dates from your $b1 string as an array of strings. Assuming all dates have the same format like your example. Fiddle with regex at https://regex101.com/

Upvotes: 0

JonR85
JonR85

Reputation: 728

Looks like you're trying to use more of a Java solution. In Powershell you can use 'ForEach'

$b1 = 'set-aduser -identity 3423-234-23-42-432 dorstm -replace @{ geboortedatum = 01-08-1997 } waarde_org = 02-08-1997'

foreach ($b in $b1) {

     if ( $b -contains '=') {
        $f = $j
     }
 }

Note: $b in the foreach loop condition can be anything you want it to be just like $i in Java.

Upvotes: 1

Gert Jan Kraaijeveld
Gert Jan Kraaijeveld

Reputation: 1187

If you want to get the index of the strings you are searching for: there's a method for that:

$b1.IndexOf('02-08-1997')
$b1.IndexOf('01-08-1997')

No need to write loops. For simple things like this .Net has a working method for you.

Upvotes: 0

Related Questions