0

I have an array with some server data and have following script:

Write-Host "`nRemoving servers' accounts from AD:" -ForegroundColor Green

for ($j=0; $j-le $screenObj.Length; $j++)
{if (($screenObj[$j].Domain -ne "Unknown") -and ($screenObj.Where({$_ -ne ""})))
 {Try {Remove-ADComputer $screenObj[$j].ServerName -Server $screenObj[$j].Domain -Confirm:$false -WhatIf
  Write-Host $screenObj[$j].ServerName "deleted." -ForegroundColor DarkYellow}
  Catch {Write-Host $screenObj[$j].ServerName ":" $_.Exception.InnerException.Message -ForegroundColor Red}
 }
 }

It gives me following output:

Removing servers' accounts from AD:
What if: Performing the operation "Remove" on target "CN=Server1,OU=Application - With WINS,OU=Application,OU=W2K3,OU=Servers,OU=MY,DC=corp,DC=mycorp,DC=net".
Server1 deleted.
What if: Performing the operation "Remove" on target "CN=Server2,OU=Application - With WINS,OU=Application,OU=W2K3,OU=Servers,OU=MY,DC=corp,DC=mycorp,DC=net".
Server2 deleted.
What if: Performing the operation "Remove" on target "CN=Server3,OU=IIS,OU=W2K8,OU=Servers,OU=Europe,DC=TKMAXX,DC=mycorp,DC=net".
Server3 deleted.
What if: Performing the operation "Remove" on target "CN=Server4,OU=IIS,OU=W2K8,OU=Servers,OU=Europe,DC=TKMAXX,DC=mycorp,DC=net".
Server4 deleted.
 : The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.


I couldn't identify why is the last line in the output is coming as
: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

Can someone explain this and help me to resolve this unknown warning?
Also, please let me know if there are better ways to achieve the desired output.
Note: I'm using -WhatIf option so that the servers aren't actually deleted.

1
  • 1
    Change $j-le $screenObj.Length to $j -lt $screenObj.Length in the for loop. (less-than, instead of less-than-or-equals) Commented Mar 27, 2021 at 16:14

1 Answer 1

1

Your for loop condition counts from 0 through $screenObj.Length, meaning that in the last iteration of the loop $screenObj[$i] will always resolve to $null - change the -le operator to -lt to fix it:

for ($j = 0; $j -lt $screenObj.Length; $j++)
{ 
  # ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @mathias-r-jessen for rescuing me. I was confident that I was so close but I failed to notice that incorrect operator. The issue is resolved :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.