Looping through an array

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 6 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
sekou2331
Posts: 318
Last visit: Sat Oct 28, 2023 7:46 am

Looping through an array

Post by sekou2331 »

Hi,

I want to know what is a good way to loop through an array and only print every thing before a certain point. I tired the below with no results. Is it best to use a foreach-object. Also can you please give me an example.
  1. $array = @("test1", "test2", "test3", "stop")
  2. foreach ($element in $array)
  3. {
  4. if (!($element -match "stop")) {
  5.     $_
  6. }
  7. }
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Looping through an array

Post by jvierra »

  1. $array = @("test1", "test2", "test3", "stop",'test4','test5')
  2. foreach ($element in $array) {
  3.     if($element -match "stop"){break}
  4.     $element
  5. }
User avatar
sekou2331
Posts: 318
Last visit: Sat Oct 28, 2023 7:46 am

Re: Looping through an array

Post by sekou2331 »

thanks! one last question how can i do it with -casesensitive? he below doesnt work
  1. $array = @("test1", "test2", "Test3", "test3" , 'test4', 'test5')
  2. foreach ($element in $array -casesensitive)
  3. {
  4.     if ($element -match "test3") { break }
  5.     $element
  6. }
User avatar
sekou2331
Posts: 318
Last visit: Sat Oct 28, 2023 7:46 am

Re: Looping through an array

Post by sekou2331 »

Sorry put it in the wrong please.


$array = @("test1", "test2", "Test3", "test3" , 'test4', 'test5')
foreach ($element in $)
{
if ($element -match "test3" -casesensitive) { break }
$element
}
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Looping through an array

Post by jvierra »

help about_Regular_Expressions
User avatar
sekou2331
Posts: 318
Last visit: Sat Oct 28, 2023 7:46 am

Re: Looping through an array

Post by sekou2331 »

Ok thanks got this to work with -cmatch
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Looping through an array

Post by jvierra »

Great. I wanted you to see where ot go to get the details on the use of RegEx in PowerShell.

Also review: help about_operators
This topic is 6 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked