一個糾結的創建AD賬號和郵箱的腳本

寫的很長,實際有用的也就那麼幾行,j_0057.gif

“add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
import-module activedirectory

new-aduser -name $ADDisplayName -samaccountname $ADUserLogin -AccountExpirationDate $ADUserAccountExpire -EmailAddress $ADUserEmail `
 -Department $ADUserDept -EmployeeID $ADEmployeeID -Company "test" -GivenName $ADUserFirst -Surname $ADUserLast -DisplayName $ADDisplayName `
 -Initials $ADUserInitials -Title $ADUserTitle -Manager $ADUserMgr -city $ADUserCity -OfficePhone $ADUserPhone -office $ADUserCountry -UserPrincipalName $ADUpn -Path $testUserDN -server $dcServer

Set-ADAccountPassword -Identity $ADUserLogin -NewPassword (ConvertTo-SecureString -AsPlainText "Rumer@2017!" -Force) -server $dcServer”



add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
import-module activedirectory

#############importing definitions from settings directory############
$testDefaults = import-csv c:\ad-configs\test-DL-Group-Settings-test.csv
$CounterCountry = 0
$CounterCity = 0
$CounterDLDeptName = 0
$ClosestDC = "mpt-dc1.test.com"
foreach($Country in $testDefaults){
if($Country.Country -ge 0){$CounterCountry++}}
foreach($City in $testDefaults){if($City.City -ge 0){$CounterCity++}}
foreach($Department in $testDefaults){if($Department.DLName -ge 0){$CounterDLDeptName++}}
write-host "Importing definitions from c:\ad-configs\test-DL-Group-Settings.csv"
write-host There are $CounterCountry Countries
write-host There are $CounterCity Cities
write-host There are $CounterDLDeptName Departments
start-sleep -s 2




function settestADCustomValues{


}
function assigntestID{
param([string]$checkIDNumber)
$notassigned = 1
while($notassigned){
    $checkIDNumber = read-host "Please Enter test Employee ID number if known, if not available type s  --> "
    
    if(($checkIDNumber -eq "S") -or ($checkIDNumber -eq "s")){
        write-host "Skipping... assigned value needupdate to field"
        $checkIDNumber = "needupdate"
        $notassigned = 0
        return $checkIDNumber
        }
        else{
        $check = get-aduser -properties EmployeeID -Filter{EmployeeID -eq $checkIDNumber}
        if($check){
          write-host "Employee ID number is already assigned.Please try again or type s to skip -->"
        }
        else{
        
            write-host "The ID you typed in hasn't been used yet. Assigning..."
            $notassigned = 0
            return $checkIDNumber
            
            }
        }
}
}
function checkEMailAddress{
param([string]$checkAddress)
$reassign = 1
while($reassign){

if(get-recipient -identity $checkAddress){
        write-host "Email is not available."
        $checkAddress = read-host "Please enter a new email address for user (@test.com will be added automatically): "
        $checkAddress = $checkAddress + "@test.com"
        $reassign = 1
        }
        else
        {
        write-host "Email is available, don't worry about red text"
        start-sleep -s 2
        $reassign = 0
        }
}
return $checkAddress
}
function createADuser{
function assignDefaultADGroups{
}

function send-summary{
param([string]$issuenumber,$samName,[string]$emailTo,[string]$adminName,[string]$server,$newBody)
$smtp = new-object Net.Mail.smtpClient($server)
$msg = new-object Net.Mail.MailMessage
$from = "[email protected]"
$msg.ReplyTo = "[email protected]"
$msg.To.Add($emailTo)
$subject="Disabled AD User Script Execution Log for: $samName"
$prepend = "<b>Reference Issuetrak Ticket: <a href='http://issuetrak.test.com/Issue_View.asp?IssueNbr=" + $issuenumber + "'>" + $issuenumber + "</a></b><br>"
$newBody = $prepend + $newBody
$x = 0    
     for( $x = 0;$x -lt $samName.memberof.count;$x++){
 }
$msg = $newBody
write-host "Sending Email"
send-mailmessage -smtpserver mpt-ex1.test.com -To $emailTo -Subject $subject -from $from -BodyAsHTML -Body $msg    
}    
function listCountries{
    write-host "Please select from the following list of countries that the employee will be located in: "
    [int]$testCountry = 600
    [int]$count = 0
    Foreach($item in $testCountries){
        $count= $count + 1
        write-host "$count $item"}
    $testCountry = read-host "Please select country number: 1 - $count --> "
return ($testCountry - 1)
}
function gettestGroup{
return $groupObject
}

function getManager{
clear-host
    [int]$count = 0
    [string]$nameString = $NULL
    $nameString = read-host "Please enter the manager's name to lookup, or enter none if not needed (Doesn't have to be exact) --> "
    if($nameString.tolower() -eq "none"){
    return $nameString
    
    }
    else{
   $matchManagers = $NULL
        $nameString = $nameString + "*"
       
            $matchManagers = get-aduser -properties Displayname,samaccountname -Filter{name -like $nameString}
         do{
                 clear-host
                 foreach($name in $matchManagers)   {
                 $count = $count + 1
                 write-host "$count $name.Name"
                 }
                 write-host Please select the correct manager by entering the correct number 1 to $matchManagers.count
                 
                 [int]$answer = 9000
                 $answerString = read-host "Please select number --> "
                 $answer = [int]$answerString
                 } until ($answer -le ($matchManagers.count))
                 $nameString = get-aduser -Identity $matchManagers[$answer - 1].samaccountname
               return $nameString
              
           }
           
           
           
}  
function select-ADUser{
$state = 1
while($state){
    $lookupUser = read-host "What is the user's login AD name? If you don't know type lookup. ->"
    if($lookupUser -eq "lookup"){ [string]$lookupUser = fuzzy-lookup}
    try{
       $foundObject = get-aduser -properties memberof,manager,mail -Identity $lookupUser
       $state = 0}
       catch{
       write-host "Cannot find userAD name please try again."
       Start-sleep -s 2
       }
       }
       return $foundObject
}

function fuzzy-lookup{
$searchFlag = 1
while($searchFlag){
    clear-host
    write-host Lookup AD user by either firstname or last name
    write-host Please enter the part of the name you wish to lookup by
    write-host "You can type tryagain to have the function called again if no results are returned"
    write-host "Even if you only know one part of the name try to type more than 3 characters for search to be effective."
    $searchString = read-host "Enter the string you want to search for: "
    $searchString = $searchString + "*"
    $results = get-aduser -properties sn,givenName,manager,memberof,useraccountcontrol -Filter{(givenName -like $searchString) -and (enabled -eq $TRUE)}
    $searchFlag = 0  
    if($results -eq $NULL){
        write-host "No match found on first name... trying last name"
        start-sleep -s 2
        $results = get-aduser -properties sn,givenName,manager,memberof -Filter{(sn -like $searchString) -and (enabled -eq $TRUE)}
        if($results -eq $NULL){
            write-host "No match found on last name either...Try again."
            start-sleep -s 2
        $searchFlag = 1
        }
    }
    }
$count = 0
write-host "Found " $results.count
    if(!$results.count){
        write-host "Only found one match. Selecting..."
        write-host "Selected:" $results.name
        start-sleep -s 2
        $nameString = $results.samaccountname
        }
    else{
    do{
                 
                 foreach($name in $results)   {
                 $count = $count + 1
                 write-host "$count $name.Name"
                 }
                 write-host Please select the correct manager by entering the correct number 1 to $results.count
                 
                 [int]$answer = 9000
                 $answerString = read-host "Please select number --> "
                 $answer = [int]$answerString
                 } until ($answer -le ($results.count))
                 $nameString = get-aduser -Identity $results[$answer - 1].samaccountname
                 #write-host "Selected $nameString"
                 
                 }
                
                return $nameString    
}

function getDept{
clear-host
do{
write-host "Please select department user belongs to:"
$count = 0
    for($x=0;$x -lt $CounterDLDeptName;$x++){
    
    write-host $x $testDefaults[$x].Department
    }
    $selection = read-host "Please select department number: "
    $numdept = [int]$selection
    
    }until($numdept -lt $CounterDLDeptName)
    return $numdept
}
function gettestMailDB{

$maildb = get-mailboxdatabase | select name
do{
write-host "Please select correct maildatbase to place user account mailbox into: "
    $count = 0
    foreach($db in $maildb){
    $count = $count + 1
    write-host $count $db.name
    }    
   $selection = read-host "Please select DB number: "
    $numdb = [int]$selection
    
    }until($numdb -le $maildb.count)
    return $maildb[$numdb -1].name
    }

function getDefaultGroups{
param([string]$Country,[String]$atype)
$accounttype = $atype.tolower()

$securityGroup = @{}
if(($accounttype -eq "s") -or ($accounttype -eq "t")){
return $securityGroup}
$ADUserSecCount = 1
write-host "passed into function $Country and $accounttype"
switch($Country){
"China-Shanghai"{if($accounttype -eq "c"){$securityGroup[$ADUserSecCount] = "Contractors-Shanghai"} else {$securityGroup[$ADUserSecCount] = "Employees-Shanghai"}}
"China-Shenzhen"{if($accounttype -eq "c"){$securityGroup[$ADUserSecCount] = "Contractors-ShenZhen"} else {$securityGroup[$ADUserSecCount] = "Employees-Shenzhen"}}

}
write-host "after switch" $securityGroup[$ADUserSecCount]
$ADUserSecCount = 2
$wifi = "r"
$*** = "r"
if($accounttype -eq "c"){
while(($wifi.tolower() -ne "n") -and ($wifi.tolower() -ne "y")){
$wifi = read-host "Does the contractor need wifi access to corporate network y or n: "
if($wifi.tolower() -eq "y"){
    $securityGroup[$ADUserSecCount] = "Contractors-Wireless"
    $ADUserSecCount++; #need to increment index array only if answer is yes
}
}
while(($***.tolower() -ne "n") -and ($***.tolower() -ne "y")){
$*** = read-host "Does the contractor need *** access to corporate network y or n: "
if($***.tolower() -eq "y"){
    $securityGroup[$ADUserSecCount] = "Contractors-***"
}
}

}
return $securityGroup
}               
                 
function getPhoneNumber{
write-host "Enter Phone Number details, future versions will lookup country code and prepend it. no entry is fine, just press ENTER to skip."
$countryCode = read-host "Enter Country Code: "
$areaCode = read-host "Enter Province/Area Code: "
$phoneNumber = read-host "Enter Phone Number (All numerals Please:) "
$fullPhone = $countryCode + " " + $areaCode + " " + $phoneNumber
write-host "Phone number is: $fullPhone"



return $fullPhone

}

function assignADAccountType{
$ADAccountType = "h"
while(($ADAccountType.tolower() -ne "c") -and ($ADAccountType.tolower() -ne "r") -and ($ADAccountType.tolower() -ne "s") -and ($ADAccountType.tolower() -ne "t")){
    $ADAccountType = read-host "What type of account is this? (C) Contractor, (R) Regular , (T) Test, (S) Service: "
    }
return $ADAccountType
}
function assignADUserFirst{
$firstname = read-host "What is the user's first name? "
return $firstname
}
function assignADUserInitials{
$initials = read-host "What is the user's middle initial? "
return $initials
}
function assignADUserLast{
    $last = read-host "What is the user's last name? "
    return $last
    }
function assignADUserLogin{
param([string]$first,[string]$last)
$noconflict = 1
while($noconflict){    
    $login = $first.substring(0,1) + $last
try{
while(get-aduser -Identity $login){
write-host "User Login Name: $ADUserLogin already exists in our system, you will need to enter a custom one"
$login = read-host "Please enter a new user login name"
}
}
catch{
$noconflict = 0}
    }
    return $login
    }
function assignADUserMgr{

$loopFlag = 1

while($loopFlag){
    $lookupUserMgr = read-host "Please type in the SAM account login name of the manager, if you don't know please type "lookup": "  
    
    switch($lookupUserMgr){
    "lookup"{
    $lookupUserMgr = fuzzy-lookup
    $UserMgr = get-aduser -properties memberof,mail -Identity $lookupUserMgr #this only namestring so is object needed?
    $loopFlag = 0
    }
    default{
        try{
        $UserMgr = get-aduser -properties memberof,manager,mail -Identity $lookupUserMgr
        $loopFlag = 0}
        catch{
        write-host "DEBUG: cannot find userAD name please try again."
        }
        }
       }
       }


write-host "SAM returned $lookupUserMgr" # this function returns SAMaccountname not whole object!
start-sleep -s 2

return $UserMgr
}
function assignADUserTitle{
$title = read-host "What is the user's job title ?"
return $title
}
function assignADUserCountry{
[int]$ADUserCountry = 600
[int]$count = 0       
########################### Select Country ######################
while($ADUserCountry -gt $testCountries.count){
$ADUserCountry = listCountries

if ($ADUserCountry -isnot [int]){
write-host "Not a number from range please try again"
start-sleep -s 2
}
}
write-host $testCountries[$ADUserCountry] is the selected one.
start-sleep -s 2
return $testCountries[$ADUserCountry]
}
function assignADUserDept{
######################### Select Department #####################
clear-host
write-host "Begin select Dept"
$ADUserDept = getDept

write-host Department selection is: $testDefaults[$ADUserDept].department
$deptString = $testDefaults[$ADUserDept].department
start-sleep -s 2
return $deptString
}    
function assignADUserLocation{
clear-host
write-host "Begin Select User Location (City) Field"

do{
write-host "Please select site (City) user belongs to:"
$count = 0
$Site = ""
    for($x=0;$x -lt $CounterCity;$x++){
    
    write-host $x $testDefaults[$x].City
    }
    $selection = read-host "Please select site (City) number: "
    $numCity = [int]$selection
    
    }until($numCity -lt $CounterCity)
    $Site = $testDefaults[$numCity].City
    write-host This is site select $site
    return $Site
    }

function assignADUserPhone{
clear-host
write-host "Begin Enter User Phone Number"
$phoneNumber = getPhoneNumber

start-sleep -s 2
return $phoneNumber
}
function createtestMail{
$createEMail = "r"
while(($createEMail.tolower() -ne "n") -and ($createEMail.tolower() -ne "y")){
$createEMail = read-host "Do you need to create an email address for this account? (y/n): "

}
return $createEmail
}


function assignADUserEMail{
############################# Need to create mailbox #############
$createEmail = "y"
if($createEMail.tolower() -eq "y"){
    write-host "determining of default E-mail addresses are assignable.. "
$Address = $ADUserFirst + "_" + $ADUserLast + "@test.com"
    $ADUserEMail = checkEMailAddress $Address
write-host "Email address default for user is: $ADUserEmail"
    }

return $ADUserEmail

}

function queryConnectionDC{
param([string]$mailserver)

$closestDC = gwmi -computername $mailserver win32_ntdomain | select domaincontrollername
$closestDC = $closestDC[1].domaincontrollername.tostring()
$closestDC = $closestDC.substring(2)
$closestDC = $closestDC + ".test.com"

write-host $mailserver is talking to $closestDC
return $closestDC
}

function createADUser{
}
function replicateToDCs{
param([string]$sourceDC)
$currentDC = get-addomaincontroller

repadmin /syncall $sourceDC "DC=test,DC=com" /d /e
write-host "Sleeping for 5 seconds to allow all changes to replicate successfully first"
start-sleep -s 5

}

#################### Main Body #####################################################################################
[string]$CreatedBy=$env:username
write-host "Starting User Creation Script by $CreatedBy"
write-host "This tool will log all input fields and send a final copy of the script results to Worldwide IT team"
write-host "Please wait..."
start-sleep -s 5
$currentDC = get-addomaincontroller
$testAddresses = gc addresses.txt
$testPostalCode = gc postalcodes.txt
$testSites = gc sitelist.txt
$testCountries = gc country.txt
$testJobList = gc jobdesc.txt
$testDept = gc dept.txt
$testCountryCode = gc countrycodes-phone.txt
$issueNumberFlag = 0
$ADUserLog = $NULL
$ADUserSecGroups = @{}
clear-host
$issueNumber = read-host "Please enter the issuetrak ticket number: "
################################## Begin Call functions ###################################################################
write-host "Version Number: " $scriptversion
start-sleep -s 2
$ADEmployeeID = assigntestID
write-host "testID variable has been assigned: $ADEmployeeID"
$ADAccountType = assignADAccountType
$ADUserFirst = assignADUserFirst
$ADUserInitials = assignADUserInitials
$ADUserLast = assignADUserLast
$ADUserLogin = assignADUserLogin $ADUserFirst $ADUserLast
$ADUserMgr = assignADUserMgr
$ADUserTitle = assignADUserTitle
$ADUserCountry = assignADUserCountry # this is using old static def for sites... consider changing in next version.
$ADUserDept = assignADUserDept
$ADUserPhone = assignADUserPhone
$ADUserCity = assignADUserLocation #this is the site location it will be assigned to the City field in address
$createEMail = "r"
while(($createEMail.tolower() -ne "n") -and ($createEMail.tolower() -ne "y")){
$createEMail = read-host "Do you need to create an email address for this account? (y/n): "
}
############## Creating email address ################
if($createEMail -eq "y"){
$ADUserEmail = assignADUserEMail
$dbnameSelect = gettestMailDB
write-host "Enabling mailbox on database target: " $dbnameSelect
}
else {$ADUserEmail=""}

$ADUserSecGroups = getDefaultGroups $ADUserCountry $ADAccountType #send country to function to return array list of defaults
$ADUserSecCount = 2
################ Check to see if contractor needs *** and Wifi Access ##############
start-sleep -s 1

if($ADAccountType.tolower() -eq "c"){
$ADUserAccountExpire = get-date
$ADUserAccountExpire = $ADUserAccountExpire.addDays(90)
write-host "By default contractor accounts are set to 90 days expiration from creation date. which is: " $ADUserAccountExpire.ToShortDateString()
write-host "We will allow modifications to this later"
start-sleep -s 2
}
$ChangeFlag = 1
######################################## End of Main first pass questions for administrator next section is review #################################
while($ChangeFlag){
clear-host
write-host "AD User Creation Summary" -backgroundcolor yellow -foregroundcolor red
write-host "Issuetrak Ticket Number: " $issueNumber "Administrator ID: " $CreatedBy   -backgroundcolor yellow -foregroundcolor red
write-host "A.)First: " -nonewline; write-host $ADUserFirst -foregroundcolor green
write-host "B.)MI: " -nonewline; write-host $ADUserInitials -foregroundcolor green
write-host "C.)Last: " -nonewline; write-host $ADUserLast -foregroundcolor green
write-host "D.)Account Type: " -nonewline; write-host $ADAccountType -foregroundcolor green
write-host "E.)ADLogin: " -nonewline; write-host $ADUserLogin -foregroundcolor green
write-host "F.)Title: " -nonewline; write-host $ADUserTitle -foregroundcolor green
write-host "G.)E-Mail: " -nonewline; write-host $ADUserEMail -foregroundcolor green
write-host "H.)Location: " -nonewline; write-host $ADUserCountry -foregroundcolor green
write-host "I.)Dept: " -nonewline;write-host $ADUserDept -foregroundcolor green
if($ADAccountType.tolower() -eq "c"){
write-host "J.) Manager: " -nonewline; write-host $ADUserMgr.name -foregroundcolor green
write-host "K.) Account Expires: " -nonewline; write-host $ADUserAccountExpire.toShortDateSTring() -foregroundcolor green

}
else{
    write-host "J.) Manager: " -nonewline; write-host $ADUserMgr.name -foregroundcolor green
    
    }
write-host "L.) User Will be Assigned to these groups: "
    for($x=1;$x -le $ADUserSecGroups.count;$x++) {
    write-host $ADUserSecGroups[$x] -foregroundcolor green
    }
write-host "M.) City: " -nonewline; write-host $ADUserCity -foregroundcolor green
write-host "N.) Phone Number: " -nonewline; write-host $ADUserPhone -foregroundcolor green

$selection = "r"

while(($selection.tolower() -ne "n") -and ($selection.tolower() -ne "y")){
    $selection = read-host "Do you wish to commit these changes? "
}
################################### Add commit changes section this is where the actual object starts to be instantiated.
If($selection.tolower() -eq "y"){
write-host "Committing Changes...."
switch($ADUserCountry){
"China-Shanghai"{$exeServer="sha-dc1.test.com"; $mailserver="sha-ex1.test.com"}
"China-Shenzhen"{$exeServer="sha-dc1.test.com"; $mailserver="sha-ex1.test.com"}

}
[string]$dcServer
$dcServer = queryConnectionDC $mailserver


write-host "Creating Account on "  $dcServer
start-sleep -s 1
$ADDisplayName = $ADUserFirst + " " + $ADUserLast
$ADUpn = $ADUserlogin + "@test.com"
$testUserDN = "CN=Users,DC=test,DC=com"
switch($ADUserCountry){
"China-Shanghai"{$testUserDN = "OU=Shanghai,OU=Users,OU=test China,DC=test,DC=com" }
"China-Shenzhen"{$testUserDN = "OU=Shenzhen,OU=Users,OU=test China,DC=test,DC=com" }

}

if($ADAccountType.tolower() -eq "c"){
new-aduser -name $ADDisplayName -samaccountname $ADUserLogin -AccountExpirationDate $ADUserAccountExpire -EmailAddress $ADUserEmail `
 -Department $ADUserDept -EmployeeID $ADEmployeeID -Company "test" -GivenName $ADUserFirst -Surname $ADUserLast -DisplayName $ADDisplayName `
 -Initials $ADUserInitials -Title $ADUserTitle -Manager $ADUserMgr -city $ADUserCity -OfficePhone $ADUserPhone -office $ADUserCountry -UserPrincipalName $ADUpn -Path $testUserDN -server $dcServer
$accountConfirm = read-host "Did the account create successfully without error messages? If so, press Y, else press CTRL-C and notify Edmund"
 
}
else{
############################ Create AD Account below with default fields filled in ###################################
new-aduser -name $ADDisplayName -samaccountname $ADUserLogin  -EmailAddress $ADUserEmail -GivenName $ADUserFirst -Surname $ADUserLast -DisplayName $ADDisplayName `
-Department $ADUserDept -Initials $ADUserInitials -Title $ADUserTitle -Company "test" -OfficePhone $ADUserPhone `
-Manager $ADUserMgr.samaccountname -employeeID $ADEmployeeID -Office $ADUserCountry -city $ADUserCity -UserPrincipalName $ADUpn -Path $testUserDN -Server $dcServer
$accountConfirm = read-host "Did the account create successfully without error messages? If so, press Y, else press CTRL-C and notify Edmund"
}

$pwdSelection = "r"
do{
    try{
    write-host "Assigning Default password Re@dy2Work!"
    Set-ADAccountPassword -Identity $ADUserLogin -NewPassword (ConvertTo-SecureString -AsPlainText "Rumer@2017!" -Force) -server $dcServer
    set-aduser $ADUserLogin -enabled $TRUE -server $dcServer
    }
    catch{
    }
    write-host "User needs to be added to security groups..."
    $ADUserSecGroups
    for($x =1; $x -le $ADUserSecGroups.count; $x++){
    write-host "Adding user to group: " $ADUserSecGroups[$x]
    try{
        Add-ADGroupMember -Identity $ADUserSecGroups[$x] -members $ADUserLogin -server $dcServer
    }
    catch{}
}

write-host "Need to replicate AD changes to and from Mail server DC"
start-sleep -s 3
replicateToDCs $currentDC.name
replicateToDCs $dcServer

}

while(!(get-aduser -identity $ADUserLogin -server $dcServer))
start-sleep -s 2
if($createEMail -eq "y"){
do{
try{
Enable-Mailbox -identity $ADUserLogin -database $dbnameSelect -domaincontroller $dcServer
}
catch{}
write-host "Waiting for AD Object Sync sleep for 10 seconds ignore error message "
start-sleep -s 10

}while(!(get-mailbox -identity $ADUserLogin -domaincontroller $dcServer))
}

$ChangeFlag = 0
clear-host
if($createEMail -eq "y"){
write-host "Mail account created successfully, moving to lync enable, need to call replicate first"
start-sleep -s 4
replicateToDCs $dcServer

clear-host

$createLync = read-host "Do you wish to enable Lync for this user? (y/n) "
if($createLync -eq "y" -or $createLync -eq "Y"){  
write-host "Enabling Lync for user needs you to enter your admin credentials again please type them in after the prompt"
start-sleep -s 5
$credential = get-credential $env:username
$session = New-PSSession -ConnectionUri "https://us-lync.test.com/OcsPowershell" -Credential $credential
Import-PsSession $session
$ADCSDisplay = $ADUserFirst + " " + $ADUserLast
$ADSIP = "sip:" + $ADUserEmail
Enable-CsUser -Identity $ADCSDisplay -RegistrarPool "us-lync.test.com" -Sipaddress $ADSIP

get-csuser
remove-PsSession $session
}
}
}
################ End Commit changes section ######################
else{
    $changechoice = read-host "What would you like to change A - L: "
    switch($changechoice.tolower()){
    
    "d"{$ADAccountType = assignADAccountType; $ADUserSecGroups = getDefaultGroups $ADUserCountry $ADAccountType }
    "a"{$ADUserFirst = assignADUserFirst; $ADUserLogin = assignADUserLogin $ADUserFirst $ADUserLast; $ADUserEmail = assignADUserEmail }
    "b"{$ADUserInitials = assignADUserInitials}
    "c"{$ADUserLast = assignADUserLast; $ADUserLogin = assignADUserLogin $ADUserFirst $ADUserLast; $ADUserEmail = assignADUserEmail}
    "e"{$ADUserLogin = assignADUserLogin $ADUserFirst $ADUserLast}
    "f"{$ADUserTitle = assignADUserTitle}
    "g"{$ADUserEmail = assignADUserEMail}
    "h"{$ADUserCountry = assignADUserCountry; $ADUserSecGroups = getDefaultGroups $ADUserCountry $ADAccountType}
    "i"{$ADUserDept = assignADUserDept}
    "j"{$ADUserMgr = assignADUserMgr}
    "n"{$ADUserPhone = assignADUserPhone}
    default{write-host "no change select or input invalid "; start-sleep -s 3}
    }
    
}
}
$ChangeFlag = 0
        ######################### Change menu selection options here ########################################
$ADUserLogDate = get-date
$ADUserLog = "<table><tr><td>Issuetrak Ticket Number:></td><td> <a href='http://web.test.com/Issue_View.asp?IssueNbr=" + $issueNumber + "'>" + $issueNumber + "</a></td></tr>"

$ADUserLog = $ADUserLog + "<tr><td>Script Version: </td><td>" + $scriptversion + "</td></tr>"

$ADUserLog = $ADUserLog + "<tr><td>Script Executed by: </td><td>" + $CreatedBy + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>Date Executed: </td><td>" + $ADUserLogDate.toshortdatestring() + "</td></tr>"
switch($ADAccountType){
"r" {$ADUserLog = $ADUserLog + "<tr><td>ADAccount Type: </td><td>Regular Employee</td></tr>"}
"c" {$ADUserLog = $ADUserLog + "<tr><td>ADAccount Type: </td><td>Contractor</td></tr>"}
"s" {$ADUserLog = $ADUserLog + "<tr><td>ADAccount Type: </td><td>Service Account</td></tr>"}
"t" {$ADUserLog = $ADUserLog + "<tr><td>ADAccount Type: </td><td>IT Test</td></tr>"}
}
$ADUserLog = $ADUserLog + "<tr><td>ADUser First:</td><td> " + $ADUserFirst + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Last:</td><td> " + $ADUserLast + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Middle:</td><td> " + $ADUserInitials + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Login:</td><td> " + $ADUserLogin + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Default Password:</td><td>Re@dy2Work!</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Title:</td><td> " + $ADUserTitle + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Manager:</td><td> " + $ADUserMgr.name + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Dept: </td><td> " + $ADUserDept + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Location: </td><td> " + $ADUserCountry + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser Email: </td><td> " + $ADUserEMail + "</td></tr>"
$ADUserLog = $ADUserLog + "<tr><td>ADUser EmployeeID: </td><td> " + $ADEmployeeID + "</td></tr>"
if($createEMail -eq "y"){
$ADUserLog = $ADUserLog + "<tr><td>ADUser Email Enabled: </td><td>YES</td></tr>"}
for($x =1; $x -le $ADUserSecGroups.count; $x++){
$ADUserLog = $ADUserLog + "<tr><td>ADUser Groups:</td><td>" + $ADUserSecGroups[$x] + "</td></tr>"
}
######### Sending Logs to IT and setup welcome email to mgr ###########################
write-host "Sending Log to it"
$smtp = new-object Net.Mail.smtpClient($server)
$msg = new-object Net.Mail.MailMessage
$from = "[email protected]"
$msg.ReplyTo = "[email protected]"
$subject="Adding AD User Script Execution Log for: $ADDisplayName"
$msg = $ADUserLog
write-host "Sending Email"
send-mailmessage -smtpserver mpt-ex1.test.com -To [email protected] -Subject $subject -from $from -BodyAsHTML -Body $msg    

$mgrMaillookup = get-aduser -identity $ADUserMgr -properties mail,displayName
$mgrMail = $mgrMaillookup.mail
$toMgr = $mgrMail
$smtp = new-object Net.Mail.smtpClient($server)
$msg = new-object Net.Mail.MailMessage
$from = "[email protected]"
$msg.ReplyTo = "[email protected]"
$subject="ATTN: Manager, this is the Employee Setup Information for $ADDisplayName"
$welcomeBLOB = "Hello: " + $mgrMail.displayName + "<br><p>Below is the new user information </p><br>"
$msg = $welcomeBLOB + $ADUserLog
write-host Sending Email to manager $mgrMail.displayName
send-mailmessage -smtpserver mpt-ex1.test.com -To $toMgr -Subject $subject -from $from -BodyAsHTML -Body $msg    
start-sleep -s 3
$issueNumberInt = [int]$issueNumber
set-aduser -Identity $ADUserLogin -add @{testUserCreateTicket = $issueNumberInt} -server $dcServer
set-aduser -Identity $ADUserLogin -replace @{testADobjectCreator = $CreatedBy} -server $dcServer
switch($ADUserCountry){
"China-Shanghai"{set-aduser -Identity $ADUserLogin -streetaddress $testAddresses[0] -server $dcServer
                 set-aduser -Identity $ADUserLogin -postalcode $testPostalcode[0] -server $dcServer
                 }
"China-Shenzhen"{set-aduser -Identity $ADUserLogin -streetaddress $testAddresses[1] -server $dcServer
                 set-aduser -Identity $ADUserLogin -postalcode $testPostalCode[1] -server $dcServer
                 }
}
switch($ADAccountType){
"s"{set-aduser -Identity $ADUserLogin -department "#Service Account" -server $dcServer
    set-aduser -Identity $ADUserLogin -title "#Service Account" -server $dcServer
    
    $prependPound = "#" + $ADUserFirst
    set-aduser -Identity $ADUserLogin -GivenName  $prependPound -server $dcServer
    
    $descriptionServiceAccount = read-host "Enter a description for the service account or skip -->"
    set-aduser -identity $ADUserLogin -description $descriptionServiceAccount -server $dcServer
    }
    
}
start-sleep -s 5
#invoke-command -computer sac-schemus -ScriptBlock {$synccmd="sleep 15; c:\Progra~2\schemus\schemusc.exe -config Mail-Config"; invoke-expression $synccmd}    

    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章