PowerShell function calling itself is loopy

Copper Contributor
I'm terrible at PowerShell.  But, I'm writing a PS script to add the distinguishedName of specific users more easily to the authOrig attribute in AD. If you aren't familiar, you can't just modify this attribute in ADUC without first adding at least one value using a PS command. And if you aren't familiar as to why someone may want to do that, that attribute determines who is allowed to send email to a Group/DL/etc.
 
Anyway, I created a function that checks if the Group in question is legitimate and if not, it just recalls the function over again until the user gets it right. The issue is that it seems to be keeping track of failures and reruns the function that many times. I's like it needs to "unloop" itself. Anyone here have a clue as what I'm doing wrong and what I could do right?
 
Here's my (crappy) code of the function:
 

 

function Get-Group {
Write-Host
try {
$groupName = Read-Host -Prompt "Enter name of Group, or q to quit"
if ($groupName -eq "q"){Exit}
$groupInfo = Get-ADGroup -Identity $groupName
}
catch {
write-host "That Group does not exist. Please check that you entered the name correctly." -ForegroundColor Red
Write-Host
Get-Group
}

Write-Host "Name: " $groupInfo.Name -ForegroundColor Green
Write-Host "Group Type: " $groupInfo.GroupCategory -ForegroundColor Green
Write-Host

$RightGroup = Read-Host -Prompt "Is this the correct Group? (Yes/No/Cancel)"

if ($RightGroup -eq "Cancel" -or $RightGroup -eq "c" -or $RightGroup -eq "C") { Exit }
elseif ($RightGroup -eq "Yes" -or $RightGroup -eq "y" -or $RightGroup -eq "Y") { return $GroupInfo}
else { Get-Group}
}

 

When you run it and enter a bad group name once, here is what happens:
 
 
KevinSmith_0-1635279657163.png

 

Thanks,
Kevin

2 Replies

Hello @KevinSmith,

Please look into this solution/approach:

https://github.com/andysvints/PowerShellIT/tree/master/PowerShellIT%20%231%20-%20Distribution%20Grou...

 

It sounds pretty similar to what you are trying to accomplish.

Add-DLSentPermission -DLName "Project management" -User andrew_svintsitsky

Group "Project Management" contain another group "logmein" user will be allowed to send emails to both of those groups. 

 

Hope that helps.

Welcome to PowerShell it can be a bit confusing. Basically you have a function but no main Script. I suggest the following:
Put your prompt for the group out of the function and have it in a do while loop that exits if q is entered.
After the group input is entered you test for Q with an if statement and you then have an else if statement that passes the group name to your function. Functions are always defined at the beginning of the script so your Main script starts after the functions are created. https://adamtheautomator.com/powershell-functions/ provides some good information on how to create a function and pass it information.

James