0

I've been trying to get usernames using employee numbers but have run into an issue. The code below works if I enter 1 employee number in the textbox but as soon as there is more than 1 employee number in the textbox, it throws a "cannot index into a null array" error and fetches none but the last username in the array.

The usernames are entered into the textbox in the following format:

Employee1
Employee2
Employee3

If I use Write-Host to print the array items before the search function then it is all fine. But as soon as the adsisearcher part is used, I get an null array error. Can anyone kindly help with this? and explain where I am going wrong?

$array = $textboxL.Text.Split("`n")

foreach($item in $array){
  $adString = (([adsisearcher]"(&(objectCategory=User)(employeenumber=$item))").findall()).properties["mailnickname"]
  $textBoxR.AppendText("$adString`r`n")
}
Tolga
  • 1
  • 1
  • 1
    Maybe ```FindAll``` isn’t finding *any*, so you might need to add error handling for invalid / non-existent employee numbers. Try breaking your ```$adString =``` line into multiple lines and check the interim results as you go, and add some logging - e.g. ```write-host $item``` at the start of your ```foreach``` so you know which item causes the problem... – mclayton Oct 30 '20 at 15:35
  • 1
    The Newline in Windows is ``"`r`n"``, not just ``"`n"`` – Theo Oct 30 '20 at 15:36
  • ... use [`system.environment.newline`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline) – iRon Oct 30 '20 at 16:11
  • @mclayton - The FindAll line definitely has an issue as when I simply read my input and print into the console (without using the findAll line) Write-Host prints the names without issues. I'll try to break it down and try again. But the weird part is that the findAll line works perfectly when its 1 input. If there are more than 1 input then it will give a null array error for all inputs except for the last line. – Tolga Oct 30 '20 at 17:10
  • @Theo My copy of the code has "`r`n", typo in the code above, my bad. – Tolga Oct 30 '20 at 17:11
  • @iRon I will give this a go! – Tolga Oct 30 '20 at 17:11
  • Try `$array = ($textboxL.Text -split '\r?\n' | Where-Object { $_ -match '\S' }).Trim()`. This makes sure you don't get empty items and also trims off leading and trailing space characters that may be entered in the textbox. – Theo Nov 04 '20 at 15:14

0 Answers0