Concatenating several foreach statements

This topic contains 2 replies, has 2 voices, and was last updated by  kenny diamond 8 months, 2 weeks ago.

  • Author
    Posts
  • #61179

    kenny diamond
    Participant

    Hello,

    Am new to powershell and trying to do an inventory in my organization. I have this 2 scripts
    A)
    function tty {
    process {
    $usr='ksilver','fsilver'
    foreach ($u in $usr) {
    $xa = (Get-ADUser $u -Properties MemberOf).memberof | Get-ADGroup
    $xb=$xa.Name
    Write-Output $xb
    }
    }
    }

    B)
    function ttu {
    process {
    $usr='ksilver','fsilver'
    foreach ($u in $usr) {
    $xa = (Get-ADUser $u -Properties MemberOf).memberof
    }
    foreach ($g in $xa) {
    $xb= (Get-ADGroup $g).Name
    Write-Output $xb
    }
    }
    }

    A works but I would like to know why B fails. I prefer keeping things in B fashion

  • #61185

    Olaf Soyk
    Participant

    First of all: Welcome to the brighter world of Powershell. 😉
    In your B)-style you iterate through all of your $usr. Then when you leave the loop there is only the result of the last users memberof in $xa. So the second loop does not have that much to do. If I'm not wrong this should work

    function ttu {
        process {
            $usr='ksilver','fsilver'
            foreach ($u in $usr) {
                $xa = (Get-ADUser $u -Properties MemberOf).memberof
                foreach ($g in $xa) {
                    $xb= (Get-ADGroup $g).Name
                    Write-Output $xb
                }
            }
        }
    }
    

    BTW: Please use the code formatting options here in the forum. It's explained in the pinned post on the top of this forum: How To Format Code In The Forums. And you should think about indentation. It makes the code much easier to read and to understand.

  • #61291

    kenny diamond
    Participant

    Hello Olaf

    Thanks a bunch. Really appreciate

You must be logged in to reply to this topic.