powershell - 使用 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:
解决方案
您可能会考虑在 Windows 窗体 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
}
希望有帮助
推荐阅读
- matrix - gnuplot 从统计矩阵给出错误的结果
- sql - 按月/年创建和关闭的记录数
- python - 使用 jnius 在 Kivy/Android 应用程序中打开日期设置
- angular - 如何使用 Angular 在 Electron 的新窗口中打开 component.html?
- java - 无法弄清楚如何让 java 运行时在标准 jdk9 运行时中加载工具的本地测试副本
- aws-cli - AWS json 输出解析
- git - 为 git 存储库中的每个文件配置编码以正确输出“git diff”
- python - 查找两个匹配形状之间的转换
- python - BigQuery DataLab 的 query_params 格式
- sql - 如何手动将 BLOB 插入 SQLite 数据库