I have the function below but I get a syntax error on line 12 when running it.
If I isolate the Get-ADuser command in Powershell ISE and pass it a name, using the same split code etc, it returns the expected user object. I am aware however that running code on my local machine may be a bit different to my script, as it establishes a remote pssession
to get Exchange commandlets for another part of the script.
I have also tried a couple of variations:
$firstlast = get-aduser -server $adDomainControllerHostName -filter {sn -like $names[1] -and givenname -like $names[0]}
$firstlast = get-aduser -server $adDomainControllerHostName -filter {GivenName -like $fn -and Surname -like $sn}
The function is called like this:
$ADProps.manager = getManagerSAMAccountName -manager $ADProps.manager -adDomainControllerHostName $DC;
$ADProps
is an array of active directory parameters like givenName, sn, samAccountName, title, department, manager, etc.
Function:
function getManagerSAMAccountName($manager, $adDomainControllerHostName){
if ($manager.trimEnd() -eq "") {
Write-Host ("*** WARNING *** : Manager name not provided.")
return ""
}
if ((test-user -samaccountname $manager -addomaincontrollerhostname $adDomainControllerHostName)) {
return $manager
} else {
$names = $manager.split("\s+")
$fn = $names[0]
$sn = $names[1]
if ($names -is [system.array]) {
$firstlast = get-aduser -server $adDomainControllerHostName -filter {(surname -eq $sn) -and (givenname -eq $fn)}
if ($firstlast -ne $null -and !($firstlast -is [array]) ) {
return $firstlast.samAccountName
}
$lastfirst = get-aduser -filter {(surname -eq $fn) -and (givenname -eq $sn)}
if ($lastfirst -ne $null -and !($lastfirst -is [array]) ) {
return $lastfirst.samAccountName
}
}
OutputLog("*** Warning: Manager name " + $manager + " appears to be ambiguous or invalid. Please provide a user id instead, such as ... Will try using the template's manager instead.")
return ""
}
}
Line which errors:
$firstlast = get-aduser -server $adDomainControllerHostName -filter {(surname -eq $sn) -and (givenname -eq $fn)}
Get-ADUser : Error parsing query: '(GivenName like $fn) -and (Surname like $sn)'. Error message: 'syntax error' at position '12'.
I have figured this out by using:
$firstlast = get-aduser -server $adDomainControllerHostName -filter "(surname -eq '$($sn)') -and (givenname -eq '$($fn)')"
Slight syntax changes like removing the {}
around it, replacing with quotes and using $() to surround the variables