PowerShell通过用户名循环

时间:2018-11-09 08:51:39

标签: powershell active-directory

我正在尝试在脚本中创建一个函数,该函数循环遍历用户名并随后创建它们。例如,当我有一个“ User1”和“ User2”时,它将创建一个“ User3”,如果我要删除其中一个用户,它将在下一次脚本运行时再次创建该用户。

编辑:我所链接的对象没有错误,我只是想知道如何使类似的东西成为可能,因为如果我对此有错,并且在链接上有一个可行的消息来源,那么我在Google上找不到任何类似的东西将不胜感激。

Import-Module ActiveDirectory

Get-ADUser -filter "enabled -eq 'false'" -SearchBase 'OU=ScriptLuuk,OU=GastAccounts,OU=Leerlingen,DC=cvo-zwfryslan,DC=nl' |
    Remove-ADUser -Confirm:$false

$ExpirationDate = Read-Host -Prompt "Enter Expiration Date like so 10/18/2018"

function Get-RandomCharacters($length, $characters) {
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
    $private:ofs = ""
    return [String]$characters[$random]
}

$password = Get-RandomCharacters -length 3 -characters 'abcdefghijklmnopqrstuvwxyz'
$password += Get-RandomCharacters -length 1 -characters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
$password += Get-RandomCharacters -length 1 -characters '1234567890'

$username = @("User1, User2, User3, User4, User5, User6, User7, User8, User9, User10")

New-ADUser `
    -Name User1 `
    -AccountPassword (ConvertTo-SecureString "$password" -AsPlainText -Force) `
    -Path "OU=ScriptLuuk,OU=GastAccounts,OU=Leerlingen,DC=cvo-zwfryslan,DC=nl" `
    -AccountExpirationDate "$ExpirationDate" `
    -Enabled 1 

Add-ADGroupMember -Identity ScriptGast -Member Luuk1

if (!(Test-Path "cvo-zwfryslan.nl\cvo\Personeel\KELU\Bureaublad\ScriptGast.txt")) {
    New-Item -Path cvo-zwfryslan.nl\cvo\Personeel\KELU\Bureaublad\ -Name ScriptGast.txt -Type "file" -Value "my new text"
    Write-Host "Created new file and text content added"
    Write-Output `n | Out-File cvo-zwfryslan.nl\cvo\Personeel\KELU\Bureaublad\ScriptGast.txt -Append
} else {
    Add-Content -Path cvo-zwfryslan.nl\cvo\Personeel\KELU\Bureaublad\ScriptGast.txt -Value "School1:$Password : $ExpirationDate"
    Write-Output `n | Out-File cvo-zwfryslan.nl\cvo\Personeel\KELU\Bureaublad\ScriptGast.txt -Append
}

1 个答案:

答案 0 :(得分:1)

您错误地定义了此数组:

$username = @("User1, User2, User3, User4, User5, User6, User7, User8, User9, User10")

它必须是:

$username = @("User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10")