Powershell nested loop

Naveen 21 Reputation points
2022-03-14T18:57:37.813+00:00

Hello folks I am trying to create a output for parameter -ou for add-aduser, however can someone help me how I can add this into an another loop where it display the value of $var and ask the user "Do you want to add this user y/n" If someone enter y, it should execute and keep the value in $var, but if someone enter n, it will go back and ask Which department does this user belongs to? Any help will be greatly appreciated!

Blockquote

@'
1.HR
2.OD
3.ELT
'@
do {
$oumove = Read-Host -Prompt 'Which department does this user belongs to?'

if ($OUmove -eq ‘1’) {

$var = “ou=users,ou=HR,ou=departments,dc=dc,dc=local”}

elseif($OUmove -eq ‘2’) {
$var = “ou=users,ou=OD,ou=departments,dc=dc,dc=local”}

elseif($OUmove -eq ‘3’) {
$var = '“ou=users,ou=ELT,ou=departments,dc=dc,dc=local”'}

else{echo ""$oumove" is a not valid number, Hint: Select a number from 1-3"}

} 

until ($oumove -gt 0 -and $oumove -lt 4)

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2022-03-14T20:30:58.127+00:00

    I don't really see the nested loop here. Your code is just prompting for a department which is independent of anything else. After that would just be an if statement asking whether you should add the user or not.

    # Get department
    do
    {
    } until (...)
    
    # Verify user
    $choice = Read-Host -Prompt "Do you want to add the user (y/n)? "
    if ($choice -eq "y") { 
        # Do your work here
    }
    

    Of course if you're doing this for a set of users then a loop makes more sense.

    $users = @('Bob', 'Sue')
    foreach ($user in $users) {
       $choice = Read-Host -Prompt "Do you want to add the user (y/n)? "
       if ($choice -ne "y") { 
          continue
    
       do
       {
       } until (...)
    }
    

    But ideally you'd wrap that choice logic into a function so it is easier to read. In fact Powershell already has PromptForchoice that can do this albeit with less than ideal code. Alternatively you could roll your own. Irrelevant you can narrow down the code and make it easier to read if you did.

    $departments = @('HR', 'OD', 'ELT')
    
    foreach ($user in $users) {
       if (ShouldAddUser $user) {
          $dept = PromptForDepartment($departments)
    
          $ou = "ou=users,ou=$dept,ou=departments,dc=dc,dc=local"
    
          # Do your work
       }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.