Difficulties with ForEach

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of Matt Joines Matt Joines 1 year, 9 months ago.

  • Author
    Posts
  • #23424
    Profile photo of Matt Joines
    Matt Joines
    Participant

    Hi All,

    I am having some difficulties with an issue I am trying to solve. The issue stems from the way folders are exported in a specific program.

    I am basically trying to use a ForEach statement to iterate through a Get-ChildItem statement and compare it to another variable. The problem is, it appears the script is comparing each line of my one variable to the entirety of the other variable.

    I guess what I am trying to ask is, how do I do a ForEach ($item in $variable){
    If ($item -like ($item in $othervariable))}

    Is such a thing even possible?

    I attached a text file of my code thus far.

    Matt

  • #23426
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I'm not sure what your code is trying to accomplish... are you trying to enumerate through two arrays at once, to see if they are the same?

  • #23427
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    Hey Matt,

    To achieve what you want, a common (though certainly not the fastest) method is using nested foreach loops.

    If you've a large dataset, you could also consider sorting the collections first and then including code to break the inner loop if the element that is read is alphabetically greater than the string you are searching for. That would speed things up a bit as well.

    • #23429
      Profile photo of Matt Joines
      Matt Joines
      Participant

      Thanks Tim, I had previously tried this and it was not working. Now that I am looking at my code I think my -like statement was wrong (using single quotes instead of double with wildcard)

      Thanks!
      Matt

  • #23428
    Profile photo of Matt Joines
    Matt Joines
    Participant

    Yes, the goal is to see if any items in those two arrays match then do some things after the fact. I haven't gotten to the after the fact part yet since this has me held up a bit. Am I attacking this from the wrong angle?

You must be logged in to reply to this topic.