使用Powershell列出AD用户并进行交互式菜单删除特定用户

所以我要做的是使用powershell将所有ADuser列出到基本的交互式菜单中,以便可以选择和删除特定用户。

到目前为止,这是我得到的所有用户,并允许我选择一个特定的用户。但是Remove-ADUser -identity $ouEntry(第18行)在我启动脚本后立即运行,并选择了所有要删除的用户,然后才可以选择特定的用户。选择一个选项并与正确的用户一起运行后,我需要它运行。我一直在寻找一个切换菜单,但由于无法正确嵌入ForEach而导致效果不佳。

感谢所有帮助。我也愿意接受其他解决方案

Clear-Host

$ouCounter = 1
$MenuArray = @()

$DomainName = ($env:USERDNSDOMAIN).split('.')[0]
$Tld = ($env:USERDNSDOMAIN).split('.')[1]

Write-Host "`nChoose the user you want to delete"



foreach ($ouEntry in ((Get-ADUser -SearchBase "DC=$DomainName,DC=$Tld" -Filter *).name))
{ 
    $("   "+$ouCounter+".`t"+$ouEntry) 
    $ouCounter++ 
    $MenuArray +=  $ouEntry + " was removed"
    $MenuArray += Remove-ADUser -identity $ouEntry
}

do
{ [int]$menuSelection = Read-Host "`n Enter Option Number"}
until ([int]$menuSelection -le $ouCounter -1)

$MenuArray[ $menuSelection-1] 

输出

Choose the user you want to delete
   1.   Administrator
   2.   Guest
   3.   user1
   4.   user2
   5.   user3
   6.   user4
   7.   user5
   8.   user6
   9.   Jon snow

 Enter Option Number: 

以前的参考文献:Making a dynamic menu in Powershell

renguopeng55 回答:使用Powershell列出AD用户并进行交互式菜单删除特定用户

您可能会考虑在Windows Forms GUI中执行此操作,因此要选择的列表可以具有滚动条。 话虽如此,您现在已经在代码中将条目作为菜单项写在屏幕上,并立即删除了该用户。

下面的代码首先将用户放入数组一次,然后从中创建一个List对象。
使用List对象的原因是因为这样很容易删除项目(与使用数组不同)。

$DomainName = ($env:USERDNSDOMAIN).Split('.')[0]
$Tld = ($env:USERDNSDOMAIN).Split('.')[1]

# get an array of users in the given OU,sorted on the Name property
$users = Get-ADUser -SearchBase "DC=$DomainName,DC=$Tld" -Filter * | Sort-Object Name

# store them in a List object for easy removal
$list = [System.Collections.Generic.List[object]]::new()
$list.AddRange($users)

# now start an endless loop for the menu handling
while ($true) { 
    Clear-Host
    # loop through the users list and build the menu
    Write-Host "`r`nChoose the user you want to delete.  Press Q to quit." -ForegroundColor Yellow
    $index = 1
    $list | ForEach-Object { "    {0}.`t{1}" -f $index++,$_.Name }

    $menuSelection = Read-Host "`r`nEnter Option Number."
    # if the user presses 'Q',exit the loop
    if ($menuSelection -eq 'Q') { break }

    # here remove the chosen user if a valid input was given
    if ([int]::TryParse($menuSelection,[ref]$index)) {
        if ($index -gt 0 -and $index -le $list.Count) {
            $userToDelete = $list[$index - 1]
            Write-Host "Removing user $($userToDelete.Name)" -ForegroundColor Cyan
            Remove-ADUser -Identity $userToDelete.DistinguishedName
            # remove the user from the list
            $list.RemoveAt($index - 1)
        }
    }
    # add a little pause and start over again
    Start-Sleep -Seconds 1
}

希望有帮助

本文链接:https://www.f2er.com/3126946.html

大家都在问