0
votes

I'm trying to come up with a powershell script to add new users in AD that our HR department can use instead of sending me emails about that.

My script will ask for which department they wanna add the new user, username and the full name:

# ##########################################
# 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";

Each time I try I run it I get this error message:

New-ADUser : Directory object not found At C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:84 char:1 + New-ADUser ` + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (CN=TYoussef Tes...diatrics,DC=Com:String) [New-ADUser], ADIdentityNotFo
undException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M icrosoft.ActiveDirectory.Management.Commands.NewADUser

Add-ADGroupMember : Cannot find an object with identity: 'yousseft' under: 'DC=TribecaPediatrics,DC=com'. At C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:92 char:1 + Add-ADGroupMember "Users" "$UName"; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (yousseft:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands. AddADGroupMember

1

1 Answers

0
votes

$result comes back as an integer so the path you're giving to New-ADUser looks like this:

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

Which is why you're getting that error message, because more than likely there is no OU with the name "0" or any of the other options "1","2" or "3".

In your switch statement you should declare what each departments OU is called so you can put the new user into that OU.

you were very close, here's how i would modify your switch statement:

# ##########################################
# 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";