Powershell为HR部门在AD中添加新用户脚本



我正在尝试编写一个powershell脚本,以便在AD中添加新用户,我们的人力资源部门可以使用,而不是发送电子邮件给我。

我的脚本将询问他们想要添加新用户,用户名和全名的部门:

# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
    Write-Warning 'Current user does not have Administrator rights'
    Write-Host 'Attempting to copy files to temporary location and restarting script'
    # Get random file name
    Do {
        $temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
    } Until (!(Test-Path -LiteralPath "$temp"))
    # Create directory
    Write-Host 'Creating temp directory... ' -NoNewLine
    New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
    Write-Host 'done.'
    # Copy script to directory
    Write-Host 'Copying script to temp directory... ' -NoNewLine
    Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
    Write-Host 'done.'
    $newScript = "$($temp)$($myInvocation.MyCommand.Name)"
    # Start new script elevated
    Write-Host 'Starting script as administrator... ' -NoNewLine
    $adminProcess = New-Object System.Diagnostics.ProcessStartInfo
    $adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
    $adminProcess.Arguments = " -File `"$newScript`""
    $adminProcess.Verb = 'runas'
    Try {
        [System.Diagnostics.Process]::Start($adminProcess) | Out-Null
    }
    Catch {
        Write-Error 'Could not start process'
        Exit 1
    }
    Write-Host 'done.'
    Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
    "RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
    "Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
    "Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
    "Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0) 
switch ($result)
    {
        0 {"You selected RN."}
        1 {"You selected Call Center."}
        2 {"You selected Management."}
        3 {"You Selected Billing."}
    }

$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"

New-ADUser `
 -Name $FName `
 -Path  "CN=Users,OU=$result,DC=Domain,DC=com" `
 -SamAccountName  $UName `
 -DisplayName $FName `
 -AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Users" "$UName";

每次我试着运行它,我得到这个错误信息:

New-ADUser: Directory object not found AtC:UsersyoussefAppDataLocalTemp ofit4gnq.1lp AddUserHR.ps1:84字符:1+ New-ADUser '+ ~~~~~~~~~~~~+ CategoryInfo: ObjectNotFound: (CN=TYoussef Tes…diatrics,DC=Com:String) [New-ADUser], ADIdentityNotFo
undException+ fulllyqualifiederrorid: ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Add-ADGroupMember:找不到id: ' youseft '的对象下:"DC = TribecaPediatrics, DC = com"。在C:UsersyoussefAppDataLocalTemp ofit4gnq.1lp AddUserHR.ps1:92字符:1+ Add-ADGroupMember "Users" "$UName";+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo: ObjectNotFound: (yousseft:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException .日志示例+ fulllyqualifiederror: setadgroupmember . validatememberparameter,Microsoft.ActiveDirectory.Management.Commands。AddADGroupMember

$result返回为整数,因此您给New-ADUser的路径看起来像这样:

"CN=Users,OU=0,DC=Domain,DC=com"

这就是为什么您会得到错误消息,因为很可能没有名称为"0"或任何其他选项为"1","2"或"3"的OU。

在switch语句中,您应该声明每个部门的OU被调用,以便您可以将新用户放入该OU中。

你非常接近,下面是我如何修改你的switch语句:

# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
    Write-Warning 'Current user does not have Administrator rights'
    Write-Host 'Attempting to copy files to temporary location and restarting script'
    # Get random file name
    Do {
        $temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
    } Until (!(Test-Path -LiteralPath "$temp"))
    # Create directory
    Write-Host 'Creating temp directory... ' -NoNewLine
    New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
    Write-Host 'done.'
    # Copy script to directory
    Write-Host 'Copying script to temp directory... ' -NoNewLine
    Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
    Write-Host 'done.'
    $newScript = "$($temp)$($myInvocation.MyCommand.Name)"
    # Start new script elevated
    Write-Host 'Starting script as administrator... ' -NoNewLine
    $adminProcess = New-Object System.Diagnostics.ProcessStartInfo
    $adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
    $adminProcess.Arguments = " -File `"$newScript`""
    $adminProcess.Verb = 'runas'
    Try {
        [System.Diagnostics.Process]::Start($adminProcess) | Out-Null
    }
    Catch {
        Write-Error 'Could not start process'
        Exit 1
    }
    Write-Host 'done.'
    Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
    "RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
    "Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
    "Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
    "Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0) 
switch ($result)
    {
        0
        {
            "You selected RN."
            $OU = "RN"
        }
        1
        {
            "You selected Call Center."
            $OU = "CallCenter"
        }
        2
        {
            "You selected Management."
            $OU = "Management"
        }
        3
        {
            "You Selected Billing."
            $OU = "Billing"
        }
    }

$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"

New-ADUser `
 -Name $FName `
 -Path  "CN=Users,OU=$OU,DC=Domain,DC=com" `
 -SamAccountName  $UName `
 -DisplayName $FName `
 -AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Users" "$UName";

最新更新