Your function looks like a good effort, but there are a number of things wrong with it and a number of best practices that aren’t being followed. There’s no reason to use BEGIN/PROCESS since you’re not accepting pipeline input on any of the parameters. There’s also no need to use the line continuation character (backtick or grave accent) at the end of a line that ends in the pipe symbol since the pipe is a natural line break. In general, try to stay away from Write-Host and use Write-Verbose instead. I rarely if ever use LDAP filters (the LDAPFilter parameter), use the filter parameter instead since it’s much easier to work with unless you have a specific reason for using LDAP filters. Remember to filter early (filter left) instead of filtering with the Where-Object cmdlet if at all possible (design for efficiency).
Here’s what I came up with, without spending too much time on it. I would recommended adding comment based help and error handling along with thoroughly testing it before saying it’s complete.
function Search-AD_Object {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateSet('_Servers',
'Application_Accounts',
'Builtin',
'Campus_Austin',
'Campus_Co-Lo',
'Campus_FLEX',
'Campus_Online',
'Campus_Saint_Augustine',
'Campus_San_Marcos',
'Computers',
'Domain Controllers',
'Exchange Groups',
'Exchange Mailboxes',
'External Contacts',
'ForeignSecurityPrincipals',
'Groups',
'IT Personnel',
'Laureate',
'LostAndFound',
'Managed Service Accounts',
'Microsoft Exchange Security Groups',
'Students',
'Students_inactive',
'Users',
'Test')]
[string]$OrganizationalUnit,
[ValidateSet('_Servers',
'_Dev_Servers',
'Faculty',
'Library',
'Finance',
'Smart_Carts',
'Staff',
'Computers',
'Users',
'Groups')]
[string]$SubOrganizationalUnit,
[ValidateNotNullorEmpty()]
[string]$ObjectName = '*',
[ValidateSet('Computer',
'User',
'Group',
'site',
'*')]
[string]$Type = '*'
)
$OUSearchBase = Get-ADObject -Filter {Name -eq $OrganizationalUnit} -SearchBase "DC=mikefrobbins,DC=com" -SearchScope OneLevel |
Select-Object -ExpandProperty DistinguishedName
If ($PSBoundParameters['SubOrganizationalUnit']) {
$OUSearchBase = Get-ADObject -Filter {Name -eq $SubOrganizationalUnit} -SearchBase $OUSearchBase -SearchScope OneLevel |
Select-Object -ExpandProperty DistinguishedName
}
Write-Verbose -Message "You're Searching in the $OUSearchBase OU"
$Search = Get-ADObject -Filter {Name -like $ObjectName -and ObjectClass -like $Type} -SearchBase $OUSearchBase |
Select-Object -Property Name
foreach ($s in $Search) {
Write-Output "Current item is: $(($s).Name)"
}
}