Nested ForEach in Powershell

Itxx
Itxx used Ask the Experts™
on
Hi all,

I'm trying this relative simple script but I think I'm not using the break function right.

First, I need to iterate through list 1(pathlist.txt). For every object in list 1, I need to iterate through list2 (hvservers.txt) and apply NTFS permissions to the paths from list1 and add the accounts from list2.

The script goes like this:
Import-Module NTFSSecurity

$pathlist = Get-Content 'C:\itxx\hvfolderpermissions\pathlist.txt'
$hvlist = Get-Content 'C:\itxx\hvfolderpermissions\hvservers.txt'


ForEach ($Path In $pathlist) {
:next

ForEach ($HVserver In $hvlist) {

Add-NTFSAccess -Path $Path -account $HVserver -AccessRights FullControl

break:next


}

}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014
Commented:
In your example, the syntax would be:
ForEach ($Path In $pathlist) {
  :next ForEach ($HVserver In $hvlist) {
    Add-NTFSAccess -Path $Path -account $HVserver -AccessRights FullControl
    break next
  }
}

Open in new window


However, based on your description, the break statement here is not needed.  Without the break statement it will iterate through items in List1, adding all items in List2.  With the break statement inserted, it would add the first permission in List2, break out of the foreach, and then continue on to the next item in List1.
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
footech is correct - you do not use break here. In general, you never use it, with very few execeptions.
But usually you try to use pipelining at least for the innermost or outermost loop. I would rewrite it hence:
ForEach ($Path In $pathlist) {
    $hvlist | % { Add-NTFSAccess -Path $Path -account $_ -AccessRights FullControl }
}

Open in new window

Author

Commented:
It works like a charm!

I was really convinced that nested ForEach would need a break.

Thanks for the help.
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
People need a break, foreach doesn't :D.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial