将多个用户添加到AD powershell脚本



我有一个powershell脚本来删除存储在变量$user下的用户,该变量取自命令行中的用户输入。如何指定多个用户并删除所有用户?

脚本低于

$User = Read-Host - Prompt 'Enter user name'
Remove-ADUser $User
Write-Host "'$user' account has been removed press any key to close..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

同意@Theo的观点,但如果你知道自己在做什么,有一个简单的解决方案:

$User = Read-Host - Prompt 'Enter user name'
foreach($u in $User.Split(',')) 
{
Remove-ADUser $u
Write-Host "'$u' account has been removed"
}
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

您只需要知道必须使用的分隔符。在这种情况下,它是",",所以您需要按模式传递登录信息:user1,user2

也许这对获得更多保存结果帮助不大。我花了几分钟才写完。也许它有帮助。


######################################
# first make sure we know what is happing..
######################################
$name = 'bob'
$AccountToDelete = Get-ADuser -filter {enabled -eq $true} -properties "displayname" | where {$_.displayname -match $name}
######################################
# then go a step further
######################################
$name = 'bob'
$AccountToDelete = Get-ADuser -filter {enabled -eq $true} -properties "displayname" | where {$_.displayname -match $name}
#show results of filter
$AccountToDelete.name
if ($AccountToDelete.count -gt 1)
{
write-warning 'more then one user:'
$AccountToDelete.name
BREAK
} 
ELSE 
{

'delete {0}' -f $AccountToDelete.name
Remove-ADUser $AccountToDelete -WhatIf
}

######################################
# improvement 1
######################################
$names = 'bob','don' 
foreach ($name in $names){
$AccountToDelete = Get-ADuser -filter {enabled -eq $true} -properties "displayname" | where {$_.displayname -match $name}
#show results of filter
$AccountToDelete.name
if ($AccountToDelete.count -gt 1)
{
write-warning 'more then one user:'
$AccountToDelete.name
BREAK
} 
ELSE 
{

'delete {0}' -f $AccountToDelete.name
Remove-ADUser $AccountToDelete -WhatIf    
}
}

######################################
# improvement 2
######################################
#now add names to delete in a notepad textfile, one name per line
<#
you can use this to create a file
PS c:usersadministator> notepad users.txt 
#>
#replace the string arrary $names = 'bob','don' 
$names = (get-content .users.txt).split('^t')
$names 
'processing {0} names...' -f $names.count
foreach ($name in $names){
$AccountToDelete = Get-ADuser -filter {enabled -eq $true} -properties "displayname" | where {$_.displayname -match $name}
#show results of filter
$AccountToDelete.name
if ($AccountToDelete.count -gt 1)
{
write-warning 'more then one user:'
$AccountToDelete.name
BREAK
} 
ELSE 
{

'delete {0}' -f $AccountToDelete.name
Remove-ADUser $AccountToDelete -WhatIf    
}
}
#finally if the script is showing you the results you need you can remove the -WhatIf 

最新更新