call depth overflow error

Hi,
The script below causes a failed due to call depth overflow with Powershell v5

How can I fix this call depth overflow problem?
function RecurseFolder

{

$f = $fold

If ($Show) { write-output $f }

If ($OU) { $ListFold = get-childitem AD:$f -force | Where-Object { ($.ObjectClass -like “container”) -or ($.ObjectClass -like “OrganizationalUnit”) } }

Else

{

try

{

$ListFold = get-childitem AD:$f -force -ErrorAction SilentlyContinue

}

catch

{

Write2Log “ERROR: because it does not exist. $f” -LogType ‘Information’

}

 

}

foreach ($e in $ListFold)

{

$FD = $e.Distinguishedname

write-output $FD

RemovePerms $FD

}

$ListFold=get-childitem AD:$f -force

|where { ($.ObjectClass -like “container”)-or($.ObjectClass -like “OrganizationalUnit”) }

foreach ($e in $ListFold) { RecurseFolder($e.Distinguishedname) }

}

 

Can you explain on what are you trying to do ? and
I request you to format the code as it is difficult to understand in normal font, below link will help you.

To remove all unknown SIDs in Active Directory domains!

function RecurseFolder
{
$f = $fold
# If ($Show) { write-output $f }
If ($OU) { $ListFold = get-childitem AD:$f -force | Where-Object { ($.ObjectClass -like “container”) -or ($.ObjectClass -like “OrganizationalUnit”) } }
Else
{
try
{
$ListFold = get-childitem AD:$f -force -ErrorAction SilentlyContinue
}
catch
{
Write2Log “ERROR: because it does not exist. $f” -LogType ‘Information’
}
}
foreach ($e in $ListFold)
{
$FD = $e.Distinguishedname
# write-output $FD
RemovePerms $FD
}
# $ListFold=get-childitem AD:$f -force
# |where { ($.ObjectClass -like “container”)-or($.ObjectClass -like “OrganizationalUnit”) }
foreach ($e in $ListFold) { RecurseFolder($e.Distinguishedname) }

}

To remove all unknown SIDs in Active Directory domains!

function RecurseFolder
{
$f = $fold
# If ($Show) { write-output $f }
If ($OU) { $ListFold = get-childitem AD:$f -force | Where-Object { ($_.ObjectClass -like "container") -or ($_.ObjectClass -like "OrganizationalUnit") } }
Else
{
try
{
$ListFold = get-childitem AD:$f -force -ErrorAction SilentlyContinue
}
catch
{
Write2Log "ERROR: because it does not exist. $f" -LogType 'Information'
}
}
foreach ($e in $ListFold)
{
$FD = $e.Distinguishedname
# write-output $FD
RemovePerms $FD
}
# $ListFold=get-childitem AD:$f -force
# |where { ($_.ObjectClass -like "container")-or($_.ObjectClass -like "OrganizationalUnit") }
foreach ($e in $ListFold) { RecurseFolder($e.Distinguishedname) }

}

Ok, so based on the script from the gallery, how are you running the script? What switches are you using when you run the script?

The RecurseFolder function may have been caught in a loop, which can cause the overflow error.

I use the following options

$Action = “/Remove”

$folder = “DC=xx, DC=xx, DC=xx”

$Opt = “/RO”