Concatenating several foreach statements

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

First of all: Welcome to the brighter world of Powershell. :wink:
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.

Hello Olaf

Thanks a bunch. Really appreciate