![](/img/trans.png)
[英]PowerShell Add users to AD group via CSV - script not adding users
[英]Add multiple users to AD powershell script
我有一個 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:\users\administator> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.