在 PowerShell 脚本中需要过滤帮助

时间:2021-03-27 16:13:04

标签: powershell powershell-5.1

我有一个包含一些服务器数据的数组,并有以下脚本:

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}
 }
 }

它给了我以下输出:

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.


我无法确定为什么输出中的最后一行是
: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

有人可以解释一下并帮助我解决这个未知警告吗?
另外,请让我知道是否有更好的方法来实现所需的输出。
注意:我使用了 -WhatIf 选项,这样服务器实际上不会被删除。

1 个答案:

答案 0 :(得分:1)

您的 for 循环条件从 0 到 $screenObj.Length,这意味着在循环的最后一次迭代中,$screenObj[$i] 将始终解析为 $null - 更改 {{1 }} 运算符到 -le 来修复它:

-lt