Suman Chhetri
Suman Chhetri

Reputation: 29

Need filtering help in PowerShell script

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.

Upvotes: 0

Views: 40

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

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++)
{ 
  # ...
}

Upvotes: 1

Related Questions