Sign in to follow this  
Followers 0
BoogY

Active Directory questions

11 posts in this topic

#1 ·  Posted (edited)

Hi there to everyone...

I'd like to create a programe that adds a remote computer to a domain.

So i made this function

Func JoinDomain($LocAdmPwd,$CompName,$DomUser,$DomPwd)
    $cmd = RunWait(@ComSpec & " /c \\Nstockpack\packages$\Tools\netdom.exe join " & $CompName & " /Domain:adacv /UserO:" & $CompName & "\xbrtfs /PasswordO:" & $LocAdmPwd & " /UserD:"& $DomUser &" /PasswordD:"& $DomPwd &" /reboot")
    If @error Then
        MsgBox(0,"ERREUR","Le pc n'as pas été ajouté au domain ADACV" & @CRLF & "Erreur : " & @error)
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    Else
        MsgBox(0,"Succès","Le pc " & $CompName & " a été ajouté au domain")
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    EndIf
EndFunc

It works, but what i want to do is show in a treeView all the Domain OUs and when the user select the domain and clicks Join to domain the computer will join the domain but in the OU that he clicked.. !!!

Can some one help me with that ?

I took a look in the adfunctions.au3 but its to complicated.. There must be a simple way of doing that !?!?

Thanks a lot for your help

Edited by BoogY

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

It's quite simple with adfunctions.au3

$strComputer = "Name of the computer object to create"
$computerOU = "Full DN of the OU to create the computer in"
$strComputerUser = "User or group that will be allowed to add the computer to the domain (SamAccountName)"
_ADCreateComputer($strComputer, $computerOU, $strComputerUser)

Did you have a look at this tool? It just seems to do what you want. Or at least you could change the code to your likings.

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

yes but it's not working like i want.

$strComputer = "Name of the computer object to create"
$computerOU = "Full DN of the OU to create the computer in"
$strComputerUser = "User or group that will be allowed to add the computer to the domain (SamAccountName)"
_ADCreateComputer($strComputer, $computerOU, $strComputerUser)

Will this juste create the computer account , or will it join the computer to the domain to ?

And how can i show all the OUs in a treeView ?

So then the user choses the ou in the treeview it will put the data in the $computerOU variable

Edited by BoogY

Share this post


Link to post
Share on other sites

Will this juste create the computer account , or will it join the computer to the domain to ?

Yes, it will create a computer account and join it to the domain.

And how can i show all the OUs in a treeView?

See the tool I mentioned above. It has a function to create the TreeView as you can see in the screenshot.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

is this the function ?

returnObjectDN()

And wich variables i must take ?

I rely dont understand his code

sorry to be so bodering but i rely need this

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Hi,

a little gui to start with:

#include <adfunctions.au3>
#include <ButtonConstants.au3>
#include <ComboConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <GUIComboBox.au3>
#include <array.au3>

Dim $arAllOU
$dnsdomain = "x.y.z" ; just your domain suffix e.g google.com
$temp = StringSplit ($dnsdomain, ".")
$dnsdomain = ""
For $i = 1 To UBound ($temp) - 1
    $dnsdomain &= ",dc=" & $temp [$i]
Next
$Form1 = GUICreate("Join PC to OU", 400, 270, 190, 115)
$Combo1 = GUICtrlCreateCombo("", 15, 80, 330, 25)
$Label1 = GUICtrlCreateLabel("OU:", 15, 55, 25, 20)
$Label2 = GUICtrlCreateLabel("Computername:", 15, 120, 80, 20)
$Input1 = GUICtrlCreateInput("", 16, 145, 120, 20)
$Button1 = GUICtrlCreateButton("O.K", 30, 210, 100, 25, 0)
$Button2 = GUICtrlCreateButton("Cancel", 175, 210, 100, 25, 0)

$arAllOU = _ADGetAllOUs () ; get all OU's of domain
_arraysort ($arAllOU)
;Fill Combo
For $i = 1 To UBound ($arAllOU) - 1
    _GUICtrlComboBox_AddString ($Combo1, $arAllOU [$i])
Next
_GUICtrlComboBox_SetCurSel($Combo1, 0)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Button2
            Exit
        Case $Button1
            $temp = Stringsplit (_GUICtrlComboBox_GetEditText ($Combo1), "\")
            $dnou = Chr (34)
            For $i = UBound ($temp) - 1 To 1 Step -1
                If $i > 1 Then
                    $dnou &= "OU=" & $temp [$i] & ","
                Else
                    $dnou &= "OU=" & $temp [$i]
                EndIf
            Next
            $dnou &= $dnsdomain & Chr (34)
            MsgBox (0,"",$DNOU)
            ;JoinDomain($LocAdmPwd,$CompName,$DomUser,$DomPwd ); original from you
            ;JoinDomain ($LocAdmPwd, GUICtrlRead ($Input1), $dnou, $DomUser, $DomPwd) ; changed with option OU, see help netdom.exe, you have to change the netdom call
            ; and you have also to define your other parameters, maybe you change to waters _ADCreateComputer suggestion
            ; you also have to code some error handlings, e.g no Computername is given: If GUICTRLRead ($input1) = "" Then.......
    EndSwitch
WEnd

;-))

Stefan

Edited by 99ojo

Share this post


Link to post
Share on other sites

WAW thats cool thanks a lot for your help. i think i can to it now... thanks agen :D

Share this post


Link to post
Share on other sites

ok i got the picture .... and i can do it..

but still id like to understand how can I sort by child parent in the OU and show'it like that in the treeView ?

Like he dows in the Joindomain Tool

So i dont understand this part right here (i think this is the one where he separets child and fother groups

;------------------------------------------------------------------------------
; Reverse the order of all the OUs so we can do an easy alpabetical sort
; on the names
;------------------------------------------------------------------------------                     
Dim $reversedAllOUsArray[1]
For $ou in $allOUsArray
    $reversedOU     = returnReversedOU($ou)
    $arrayAddStatus = _ArrayAdd($reversedAllOUsArray, $reversedOU)  
Next

;------------------------------------------------------------------------------
; Sort the array alpabetically
;------------------------------------------------------------------------------
$sortRevArrayStatus = _ArraySort($reversedAllOUsArray)      

;------------------------------------------------------------------------------
; Initialize our treeIDArray
; This will be used to look up the ID number of the GUI TreeView entries
; We need this to make nesting/child-parent relationships work.
;------------------------------------------------------------------------------
Dim $treeIDArray[UBound($reversedAllOUsArray)*2]

;------------------------------------------------------------------------------
; Return the OUs to their original format and create the TreeView Entries.
;------------------------------------------------------------------------------
$adCurrentObjectNumber = 0
For $reversedOU in $reversedAllOUsArray
    If $reversedOU = "" then 
        ContinueLoop
    EndIf
    
    ;------------------------------------------------------------------------------
    ; Reverse the order back to the orginal format  
    ;------------------------------------------------------------------------------ 
    $ou             = returnReversedOU($reversedou)
    
    ;------------------------------------------------------------------------------
    ; Calculate the additional values for this OU and check to see if its
    ; parentou has a GUI TreeID
    ;------------------------------------------------------------------------------     
    $fullOU             = StringStripWS($ou, 3)         
    $friendlyOU         = returnFriendlyName($fullOU)           
    $parentFullOU           = returnParentOU($fullOU)           
    $parentTreeID           = _ArraySearch($treeIDArray, $parentFullOU)
    
    ;------------------------------------------------------------------------------
    ; Check if this OU has a parent. If it does make this TreeView item a child
    ; of that parent.
    ;------------------------------------------------------------------------------
    If ( $parentTreeID <> "-1" ) Then   
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $parentTreeID)
    Else    
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $defaultTreeView)
    EndIf   

    ;------------------------------------------------------------------------------
    ; The returned $treeID is sequential. We can use this to cheat and emulate
    ; a hashtable.
    ;------------------------------------------------------------------------------
    $treeIDArray[$treeID] = $fullOU
    
    ;------------------------------------------------------------------------------
    ; Update the progress bar and increment the object count
    ;------------------------------------------------------------------------------     
    UpdateProgressBar(($adCurrentObjectNumber / UBound($allOUsArray)) * 100)
    UpdateProgressText($guiProgressMessage & " - Currently querying " & $friendlyOU)
    $adCurrentObjectNumber = $adCurrentObjectNumber + 1 
Next

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

ok i got the picture .... and i can do it..

but still id like to understand how can I sort by child parent in the OU and show'it like that in the treeView ?

Like he dows in the Joindomain Tool

So i dont understand this part right here (i think this is the one where he separets child and fother groups

;------------------------------------------------------------------------------
; Reverse the order of all the OUs so we can do an easy alpabetical sort
; on the names
;------------------------------------------------------------------------------                     
Dim $reversedAllOUsArray[1]
For $ou in $allOUsArray
    $reversedOU     = returnReversedOU($ou)
    $arrayAddStatus = _ArrayAdd($reversedAllOUsArray, $reversedOU)  
Next

;------------------------------------------------------------------------------
; Sort the array alpabetically
;------------------------------------------------------------------------------
$sortRevArrayStatus = _ArraySort($reversedAllOUsArray)      

;------------------------------------------------------------------------------
; Initialize our treeIDArray
; This will be used to look up the ID number of the GUI TreeView entries
; We need this to make nesting/child-parent relationships work.
;------------------------------------------------------------------------------
Dim $treeIDArray[UBound($reversedAllOUsArray)*2]

;------------------------------------------------------------------------------
; Return the OUs to their original format and create the TreeView Entries.
;------------------------------------------------------------------------------
$adCurrentObjectNumber = 0
For $reversedOU in $reversedAllOUsArray
    If $reversedOU = "" then 
        ContinueLoop
    EndIf
    
    ;------------------------------------------------------------------------------
    ; Reverse the order back to the orginal format  
    ;------------------------------------------------------------------------------ 
    $ou             = returnReversedOU($reversedou)
    
    ;------------------------------------------------------------------------------
    ; Calculate the additional values for this OU and check to see if its
    ; parentou has a GUI TreeID
    ;------------------------------------------------------------------------------     
    $fullOU             = StringStripWS($ou, 3)         
    $friendlyOU         = returnFriendlyName($fullOU)           
    $parentFullOU           = returnParentOU($fullOU)           
    $parentTreeID           = _ArraySearch($treeIDArray, $parentFullOU)
    
    ;------------------------------------------------------------------------------
    ; Check if this OU has a parent. If it does make this TreeView item a child
    ; of that parent.
    ;------------------------------------------------------------------------------
    If ( $parentTreeID <> "-1" ) Then   
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $parentTreeID)
    Else    
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $defaultTreeView)
    EndIf   

    ;------------------------------------------------------------------------------
    ; The returned $treeID is sequential. We can use this to cheat and emulate
    ; a hashtable.
    ;------------------------------------------------------------------------------
    $treeIDArray[$treeID] = $fullOU
    
    ;------------------------------------------------------------------------------
    ; Update the progress bar and increment the object count
    ;------------------------------------------------------------------------------     
    UpdateProgressBar(($adCurrentObjectNumber / UBound($allOUsArray)) * 100)
    UpdateProgressText($guiProgressMessage & " - Currently querying " & $friendlyOU)
    $adCurrentObjectNumber = $adCurrentObjectNumber + 1 
Next

Hi,

here are some changes in JoinDomain Tool.

You need a XP workstation with dsquery installed.

I run a dsquery ou >@ScriptDir & "\temp.txt" and read the output into an array.

With the array i fill the listview. (hard work and not completely finished and well)

Your part:

1) Remove more unnecessary code

2) Change some messages titles etc.

3) Code the rest for your needs if you want to (buttons, functions..) ...

;------------------------------------------------------------------------------
;
; AutoIt Version: 3.0
;
; Script Function:
;  Join Domain - A GUI to join a Active Directory domain by specifying the OU
;
;  Requires:
;  Latest version of AutoIT with COM Support
;   
;
; Author:         Walt Howd
;
; Version 1.0   03/04/2006  Initial internal release
; Version 1.1   05/05/2006  Small update. Added prompt for username and password.
; Version 1.2   18/09/2009 Changing to dsquery, remove ADODB Functions, change code to get OU in listview
;
; Copyright Walt Howd
;
; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation; either version 2 of the License, or
; any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with this program; if not, write to the Free Software
; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
;
;------------------------------------------------------------------------------

;------------------------------------------------------------------------------
; Includes and AutoIT Options
;------------------------------------------------------------------------------
#NoTrayIcon
#Include <GUIConstants.au3>
#Include <GuiListView.au3>
#Include <Array.au3>
#include <WindowsConstants.au3>
#include <adfunctions.au3>
#include <file.au3>
#include <Constants.au3>

;------------------------------------------------------------------------------
; Active Directory Constants
;------------------------------------------------------------------------------
;Const $ldapConnectionString    = "LDAP://" & $adDomainController & "/" & $adDefaultContext
Const $ouIdentifier     = "OU="
Const $cnIdentifier     = "CN="
Const $ouSeparator      = ","
Const $dsqlimit         = 2000

;------------------------------------------------------------------------------
; GUI Look and Feel Configuration
;------------------------------------------------------------------------------
$guiWidth       = 640
$guiHeight      = $guiWidth * 0.75
$guiOffset      = $guiHeight / 32
$guiBannerMessage   = "Truman State University ITS - Join Domain Tool"
$guiWindowTitle     = "Join Domain Tool"
$guiTooManyResultsTitle = "Too many results found - Please select one"
$guiJoinButtonTitle = "Join Domain"
$guiListOUSButtonTitle  = "List all OUs"
$guiProgressMessage = "Please wait while querying Active Directory"

;------------------------------------------------------------------------------
; Create the GUI
;------------------------------------------------------------------------------
$joinDomainGUI      = GUICreate($guiWindowTitle,$guiWidth,$guiHeight,-1,-1,BitOr($WS_MINIMIZEBOX,$WS_MAXIMIZEBOX,$WS_GROUP,$WS_CAPTION,$WS_POPUP,$WS_SYSMENU))

;------------------------------------------------------------------------------
; Create the banner text
;------------------------------------------------------------------------------
$bannerText     = GuiCtrlCreateLabel($guiBannerMessage, $guiOffset,$guiOffset, $guiWidth*0.75)
$bannerTextFont     = GUICtrlSetFont($bannerText, 10, 600)

;------------------------------------------------------------------------------
; Create our Join Domain button
;------------------------------------------------------------------------------
$joinButton         = GUICtrlCreateButton ($guiJoinButtonTitle,$guiOffset,$guiOffset*3,($guiWidth/3),$guiOffset*2)

;------------------------------------------------------------------------------
; Create the TreeView - This is where all the OU's will be listed
;------------------------------------------------------------------------------
$defaultTreeView    = GUICtrlCreateTreeView ($guiOffset,$guiOffset*10,($guiWidth-($guiOffset*2)),($guiHeight-($guiOffset*11)) )

;------------------------------------------------------------------------------
; Create the control to handle too many hits from an Object Search
; This will be hidden until a search with multiple hits is performed
;------------------------------------------------------------------------------
$tooManyObjectsList     = GuiCtrlCreateListView("Name|OU", $guiOffset,$guiOffset*10,($guiWidth-($guiOffset*2)),($guiHeight-($guiOffset*11)))
$hideTooManyObjectsList = GuiCtrlSetState($tooManyObjectsList, $GUI_HIDE);

;------------------------------------------------------------------------------
; Create the Progress Bar and Text controls
;------------------------------------------------------------------------------
$progressGroup      = GUICtrlCreateGroup("Progress", $guiOffset, $guiOffset*6, $guiWidth-($guiOffset*2), "54")
$progressBar        = GUICtrlCreateProgress($guiOffset*1.5,$guiOffset*7,($guiWidth-($guiOffset*3)),$guiOffset*1)
$progessBarStartAtZero  = GuiCtrlSetData ($progressBar, 0)
$progressText       = GuiCtrlCreateLabel($guiProgressMessage, $guiOffset*1.5,$guiOffset*8.5,($guiWidth-($guiOffset*3)),$guiOffset*1)

;------------------------------------------------------------------------------
; Create the Object search controls
;------------------------------------------------------------------------------
$objectSearchGroup  = GUICtrlCreateGroup("Search", $guiWidth-($guiOffset*14), $guiOffset-5, "195", "80")
$objectSearchLabel  = GuiCtrlCreateLabel("Enter username, computer or OU:", $guiWidth-($guiOffset*13), $guiOffset*2)
$objectSearchInput  = GUICtrlCreateInput("", $guiWidth-($guiOffset*13), $guiOffset*3, "100")
$objectSearchButton = GUICtrlCreateButton("Search", $guiWidth-($guiOffset*5), $guiOffset*3)

;------------------------------------------------------------------------------
; Disable the buttons until our OU enumeration is done
;------------------------------------------------------------------------------
$disableJoinButton      = GUICtrlSetState($joinButton, $GUI_DISABLE);
$disableObjectSearchButton  = GUICtrlSetState($objectSearchButton, $GUI_DISABLE);

;------------------------------------------------------------------------------
; Make the GUI Visible
;------------------------------------------------------------------------------
$joinDomainGUIVisible   = GUISetState(@SW_SHOW, $joinDomainGUI)

;------------------------------------------------------------------------------
; Query for all organizational units with dsquery
;------------------------------------------------------------------------------

Dim $allOUsArray
$pid = RunWait (@ComSpec & " /c dsquery ou -limit " & $dsqlimit & " >" & @ScriptDir & "\temp.txt", @SystemDir, @SW_HIDE)
_FileReadToArray (@ScriptDir & "\temp.txt", $allOUsArray)
FileDelete (@ScriptDir & "\temp.txt")
_ArrayDelete ($allOUsArray, 0)
;------------------------------------------------------------------------------
; Reverse the order of all the OUs so we can do an easy alpabetical sort
; on the names
;------------------------------------------------------------------------------                     
Dim $reversedAllOUsArray[1]
For $ou in $allOUsArray
    $reversedOU     = returnReversedOU($ou)
    $arrayAddStatus = _ArrayAdd($reversedAllOUsArray, $reversedOU)  
Next

;------------------------------------------------------------------------------
; Sort the array alpabetically
;------------------------------------------------------------------------------
$sortRevArrayStatus = _ArraySort($reversedAllOUsArray)      

;------------------------------------------------------------------------------
; Initialize our treeIDArray
; This will be used to look up the ID number of the GUI TreeView entries
; We need this to make nesting/child-parent relationships work.
;------------------------------------------------------------------------------
Dim $treeIDArray[UBound($reversedAllOUsArray)*2]

;------------------------------------------------------------------------------
; Return the OUs to their original format and create the TreeView Entries.
;------------------------------------------------------------------------------
$adCurrentObjectNumber = 0
For $reversedOU in $reversedAllOUsArray
    If $reversedOU = "" then 
        ContinueLoop
    EndIf
    
    ;------------------------------------------------------------------------------
    ; Reverse the order back to the orginal format  
    ;------------------------------------------------------------------------------ 
    $ou             = returnReversedOU($reversedou)
    
    ;------------------------------------------------------------------------------
    ; Calculate the additional values for this OU and check to see if its
    ; parentou has a GUI TreeID
    ;------------------------------------------------------------------------------     
    $fullOU             = StringStripWS($ou, 3)         
    $friendlyOU         = returnFriendlyName($fullOU)       
    ;$parentFullOU          = StringTrimRight (returnParentOU($fullOU),1)
    $parentFullOU = ""
    $temp = Stringsplit ($fullOU, ",")
    If $temp [0] = 4 Then 
        $parentFullOU = $fullOU
    Else
        For $i = 2 To UBound ($temp) - 1
            $parentFullOU &= $temp [$i] & ","
        Next
        $parentFullOU = StringTrimRight ($parentFullOU, 2)
    EndIf
    ;MsgBox (0,"",$parentFullOU)
    For $i = 1 To UBound ($treeIDArray) - 1
        $parentTreeID = StringInStr ($treeIDArray [$i], $parentFullOU) 
        If $parentTreeID > 0 Then 
            $parentTreeID = $i
            ExitLoop
        EndIf
    Next
    ConsoleWrite ($parentTreeID & @CRLF)
    ;------------------------------------------------------------------------------
    ; Check if this OU has a parent. If it does make this TreeView item a child
    ; of that parent.
    ;------------------------------------------------------------------------------
    If ( $parentTreeID <> 0 ) Then  
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $parentTreeID)
    Else    
        $treeID         = GUICtrlCreateTreeViewItem ($friendlyOU, $defaultTreeView)
    EndIf   
    _GUICtrlListView_RedrawItems ($defaultTreeView, 1, $treeID)
    ;------------------------------------------------------------------------------
    ; The returned $treeID is sequential. We can use this to cheat and emulate
    ; a hashtable.
    ;------------------------------------------------------------------------------
    $treeIDArray[$treeID] = $fullOU
    ;_ArrayDisplay ($treeIDArray)
    ;------------------------------------------------------------------------------
    ; Update the progress bar and increment the object count
    ;------------------------------------------------------------------------------     
    UpdateProgressBar(($adCurrentObjectNumber / UBound($allOUsArray)) * 100)
    UpdateProgressText($guiProgressMessage & " - Currently querying " & $friendlyOU)
    $adCurrentObjectNumber = $adCurrentObjectNumber + 1 
Next

;------------------------------------------------------------------------------
; Query is complete, update Progress Text
;------------------------------------------------------------------------------
UpdateProgressText("Please select an OU to join from the list below.")

;------------------------------------------------------------------------------
; Check and see if this computername is already present in AD
;------------------------------------------------------------------------------

;------------------------------------------------------------------------------
; Enable the buttons
;------------------------------------------------------------------------------
$enableJoinButton       = GUICtrlSetState($joinButton, $GUI_ENABLE);
$enableObjectSearchButton   = GUICtrlSetState($objectSearchButton, $GUI_ENABLE);

;------------------------------------------------------------------------------
; GUI Message Loop
;------------------------------------------------------------------------------
While 1
    $msg        = GUIGetMsg()
    Select
        ;-----------------------------------------------------------------------------------
        ; User clicked "Close" button
        ;-----------------------------------------------------------------------------------
        Case $msg = -3 Or $msg = -1 

            GUIDelete()
            ExitLoop
            
        ;-----------------------------------------------------------------------------------
        ; User clicked "Join Domain" button
        ;-----------------------------------------------------------------------------------            

    EndSelect
WEnd
GUIDelete()

Func returnReversedOU($ou)
    $subOUArray = StringSplit($ou, $ouSeparator)
    $reversedOU = ""
    For $i = (UBound($subOUArray) - 1 ) To 1 Step -1 
        If $i = (UBound($subOUArray) -  1 ) Then
            $reversedOU = $reversedOU & $subOUArray[$i]
        Else
            $reversedOU = $reversedOU & $ouSeparator & $subOUArray[$i]
        EndIf
    Next
    return $reversedOU
EndFunc

;------------------------------------------------------------------------------
; Replaces the Progress Text control with supplied text
;------------------------------------------------------------------------------ 
Func UpdateProgressText($text) 
    GUICtrlSetData($progressText, $text)
EndFunc

;------------------------------------------------------------------------------
; Updates the progress bar to the passed percentage
;------------------------------------------------------------------------------ 
Func UpdateProgressBar($percentage)
    GuiCtrlSetData($progressBar, $percentage)
EndFunc

;------------------------------------------------------------------------------
; Will return the current computername of the system running this script
;------------------------------------------------------------------------------ 
Func returnComputerName()
    $networkObj         = ObjCreate("WScript.Network")
    $computerName       = $networkObj.ComputerName
    return $computerName
EndFunc

;------------------------------------------------------------------------------
; Returns the friendly object name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; IT Shop
;------------------------------------------------------------------------------ 
Func returnFriendlyName($dn)
    return StringMid($dn, StringInStr($dn, "=")+1, StringInStr($dn, $ouSeparator)-(StringInStr($dn, "=")+1))
EndFunc

;------------------------------------------------------------------------------
; Returns the full OU name from a DN record:
;
; Example:
;
; The DN:
; CN=Paula,OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnFullOUfromDN($dn)
    If $dn <> "0" Then
        return StringRight($dn, StringLen($dn)-StringInStr($dn, $ouIdentifier)+1)
    Else
        return 0
    EndIf
EndFunc

;------------------------------------------------------------------------------
; Returns the parent OU name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnParentOU($fullOU)
    return StringRight($fullOU, ( StringLen($fullOU)-StringInStr($fullOU, $ouSeparator) ) )
EndFunc

;-))

Stefan

Edited by 99ojo

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Actualy i managed to do it... but i got another problem now.

When i click in the treeView the ou i need a variable to get its value but in this form

OU=Dsys,OU=Workstations,DC=microsoft,DC=com

so i can put'it in the functione to add the computer to the domain and in the selected OU.

I can get the variable with this :

$selectedOU = $treeIDArray[GUICtrlRead($defaultTreeView)]
GUICtrlSetData($txtOUPath,$selectedOU)

But it return a path like =

\Dsys\Workstations\microsoft\com

how can i change'it back in OU=Dsys,OU=Workstations,DC=microsoft,DC=com

Here is my code :

Ant thank you verymuch for your help :D thats rely cool.

#NoTrayIcon
#include <GUIConstants.au3>
#include <EditConstants.au3>
#include <adfunctions.au3>
#include <TreeViewConstants.au3>
#Include <Array.au3>

;------------------------------------------------------------------------------
; Domain details
;
; Change these three lines to match your enviroment
;------------------------------------------------------------------------------
$adDefaultContext   = "DOMAIN"
$adDomainController = "DOMAIN"
$adDomain       = "DOMAINNAME"

;------------------------------------------------------------------------------
; Username and password
;
; If you wish to be prompted for these values instead of hardcoding them
; here you may leave these blank.
;------------------------------------------------------------------------------
$adUsername     = IniRead(@ScriptDir & "\config.ini", "user", "username", "zsibni")
$adPassword     = IniRead(@ScriptDir & "\config.ini", "pwd", "pwd", "No Password")

;------------------------------------------------------------------------------
; Active Directory Constants
;------------------------------------------------------------------------------
Const $ldapConnectionString     = "LDAP://" & $adDomainController & "/" & $adDefaultContext
Const $ouIdentifier     = "OU="
Const $cnIdentifier     = "CN="
Const $ouSeparator      = ","
Const $ouSeparator2     = "\"


;------------------------------------------------------------------------------
; Prompt for the username if it is not hardcoded above
;------------------------------------------------------------------------------
If $adUsername = "" Then
    $adUsername     = InputBox("Input username", "Please enter the username of the account you wish to use to " & _
                    "join the domain. This should be just the username." & @LF & @LF & _
                    "Example:" & @LF & "jdoe")
    If @error Then 
        MsgBox(0, "Error with username - " & @error, "There was an error proccessing your username." & @LF & @LF & _
                "The username I received was:" & @LF & _
                $adUsername & @LF & @LF & _
                "Please restart this application and try again. If this problem persists you can try" & _
                "hard coding this information into this program by editing the source file.")
        Exit(900)
    EndIf
EndIf

;------------------------------------------------------------------------------
; Prompt for the password if it is not hardcoded above
;------------------------------------------------------------------------------
If $adPassword = "" Then
    $adPassword = InputBox("Input password","Please enter the password:",'','*')
    If @error Then 
        MsgBox(0,"Error with password - " & @error, "There was an error proccessing your password." & @LF & @LF & _
                "Please restart this application and try again. If this problem persists you can try" & _
                "hard coding this information into this program by editing the source file.")
        Exit(901)
    EndIf
EndIf

;------------------------------------------------------------------------------
; Initiate our ADO connection to Active Directory
;------------------------------------------------------------------------------
$connObj = objCreate("ADODB.Connection")
$connObj.Provider = "ADsDSOObject"
$connObj.ConnectionTimeout = "1"
$connObj.Open("Active Directory Provider", $adDomain & "\" & $adUsername, $adPassword)

;------------------------------------------------------------------------------
; Find and store the computer name of the system running this program
;------------------------------------------------------------------------------
$computername   = returnComputerName()

#Region ### START Koda GUI section ### Form=E:\PERSO\Scripts\MON PROJET\ADACV_un-join\JoinDomain.kxf
$frmJoinDomain = GUICreate("Join Domain ADACV", 601, 403, 611, 217)
$txtTFS = GUICtrlCreateInput("", 304, 32, 121, 21)
$lblTFS = GUICtrlCreateLabel("TFS :", 272, 32, 30, 17)
$btnJoinDomain = GUICtrlCreateButton("Join Domain", 504, 8, 89, 25, 0)
$lblDomainUser = GUICtrlCreateLabel("Domain User", 24, 8, 65, 17)
$txtDomainPasswd = GUICtrlCreateInput("", 96, 32, 121, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
$txtDomainUser = GUICtrlCreateInput("" & @UserName &"", 96, 8, 121, 21)
$lblDomainPasswd = GUICtrlCreateLabel("Domain Passwd", 8, 32, 80, 17)
$txtLocalPasswd = GUICtrlCreateInput("", 304, 8, 121, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
$Label1 = GUICtrlCreateLabel("Local Passwd", 224, 8, 70, 17)
$progressText = GUICtrlCreateLabel("Join ADACV Domain", 8, 104, 589, 57)
$defaultTreeView = GUICtrlCreateTreeView(8, 160, 585, 209)
$progressBar = GUICtrlCreateProgress(8, 376, 585, 17)
$txtOUPath = GUICtrlCreateInput("", 8, 80, 585, 21)
$lblOUPath = GUICtrlCreateLabel("OU Path :", 8, 56, 51, 17)
$btnAddOU = GUICtrlCreateButton("Ajouter OU", 504, 40, 89, 25, 0)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

;------------------------------------------------------------------------------
; Query for all organizational units
;------------------------------------------------------------------------------
$arAllOU = _ADGetAllOUs () ; get all OU's of domain
_arraysort($arAllOU)


Dim $treeIDArray[UBound($arAllOU)*2]
;------------------------------------------------------------------------------
; Return the OUs to their original format and create the TreeView Entries.
;------------------------------------------------------------------------------
$adCurrentObjectNumber = 0
For $reversedOU in $arAllOU
    If $reversedOU = "" then 
        ContinueLoop
    EndIf
    ;------------------------------------------------------------------------------
    ; Reverse the order back to the orginal format  
    ;------------------------------------------------------------------------------ 
    $ou = returnReversedOU($reversedOU)
    ;------------------------------------------------------------------------------
    ; Calculate the additional values for this OU and check to see if its
    ; parentou has a GUI TreeID
    ;------------------------------------------------------------------------------     
    $fullOU         = StringStripWS($ou, 3)         
    $friendlyOU     = returnFriendlyName($fullOU)           
    $parentFullOU   = returnParentOU($fullOU)           
    $parentTreeID   = _ArraySearch($treeIDArray, $parentFullOU)
    ;------------------------------------------------------------------------------
    ; Check if this OU has a parent. If it does make this TreeView item a child
    ; of that parent.
    ;------------------------------------------------------------------------------
    If ( $parentTreeID <> "-1" ) Then   
        $treeID = GUICtrlCreateTreeViewItem ($friendlyOU, $parentTreeID)
    Else    
        $treeID = GUICtrlCreateTreeViewItem ($friendlyOU, $defaultTreeView)
    EndIf   
    ;------------------------------------------------------------------------------
    ; The returned $treeID is sequential. We can use this to cheat and emulate
    ; a hashtable.
    ;------------------------------------------------------------------------------
    $treeIDArray[$treeID] = $fullOU
    UpdateProgressBar(($adCurrentObjectNumber / UBound($arAllOU)) * 100)
    UpdateProgressText("Currently querying " & $friendlyOU)
    $adCurrentObjectNumber = $adCurrentObjectNumber + 1
Next
;------------------------------------------------------------------------------
; Query is complete, update Progress Text
;------------------------------------------------------------------------------
UpdateProgressText("Veuillez sélectionner une OU pour ajouter la machine.")

;------------------------------------------------------------------------------
; Check and see if this computername is already present in AD
;------------------------------------------------------------------------------
$computersCN = returnObjectDN($computername, "computer")
If $computersCN <> "0" Then
    $computersOU = returnFullOUfromDN($computersCN)
    UpdateProgressText("Found this computer (" & $computername & ") in the " & _
                returnFriendlyName($computersOU) & " - This has been selected " & _
                "for you below.")
    GuiCtrlSetState(_ArraySearch($treeIDArray, $computersOU), $GUI_FOCUS)
EndIf


While 1
    $msg = GUIGetMsg()
    Select
        Case $msg = $GUI_EVENT_CLOSE
            Exit
            
        Case $msg = $btnAddOU
            $selectedOU = $treeIDArray[GUICtrlRead($defaultTreeView)]
            GUICtrlSetData($txtOUPath,$selectedOU)
            
        Case $msg = $btnJoinDomain
            $selectedOU = returnFullOUfromDN($treeIDArray[GUICtrlRead($defaultTreeView)])
;~          $LocAdmPwd = GUICtrlRead($txtLocalPasswd)
;~          $CompName = GUICtrlRead($txtTFS)
;~          $DomUser = GUICtrlRead($txtDomainUser)
;~          $DomPwd = GUICtrlRead($txtDomainPasswd)
;~          $OUPath = $selectedOU
;~          If $CompName = "" Then
;~              MsgBox(0,"ERREUR","Pas de numéro TFS")
;~          Else
;~              JoinADACV($LocAdmPwd,$CompName,$DomUser,$DomPwd,$OUPath)
;~          EndIf
    EndSelect
WEnd

;------------------------------------------------------------------------------
; Join the computer to the domain and OU
;------------------------------------------------------------------------------ 
Func JoinADACV($LocAdmPwd,$CompName,$DomUser,$DomPwd,$OUPath)
    $cmd = RunWait(@ComSpec & " /c \\Nstockpack\packages$\Tools\netdom.exe join " & $CompName & " /Domain:adacv /OU:"& $OUPath &"/UserO:" & $CompName & "\xbrtfs /PasswordO:" & $LocAdmPwd & " /UserD:"& $DomUser &" /PasswordD:"& $DomPwd &" /reboot")
    If @error Then
        MsgBox(0,"ERREUR","Le pc n'as pas été ajouté au domain ADACV" & @CRLF & "Erreur : " & @error)
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    Else
        MsgBox(0,"Succès","Le pc " & $CompName & " a été ajouté au domain")
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    EndIf
EndFunc

;------------------------------------------------------------------------------
; Searches AD via ADO for the DN of an object
; 
;
; If the DN is found then it is returned.
;
; If no match is found then 0 is returned
; 
;
; If more then one match is found then they are returned
; as a single string, separated by linebreaks.
;
; The second paramter dictates the object type to
; search for. It can either by user, computer, or
; organizationalunit. Alternatively it can be an objectclass
; your AD structure supports.
; 
;------------------------------------------------------------------------------ 
Func returnObjectDN($objectName, $objectClass)
    $objectsFoundCount          = 0
    Dim $objectsFoundNames
    
    ;------------------------------------------------------------------------------
    ; Create the ADO object and execute the search
    ;------------------------------------------------------------------------------     
    $commandObj             = objCreate("ADODB.Command")
    $commandObj.ActiveConnection        = $connObj
    $commandObj.CommandText         = "SELECT distinguishedName FROM '" & $ldapConnectionString & "' " & _
                          "WHERE objectClass='" & $objectClass & "' AND name ='" & $objectName & "'"  
    $commandObj.Properties("Page Size")     = 10000
    $commandObj.Properties("Cache Results") = True
    $commandObj.Properties("SearchScope")   = 2

    $objRecordSet               = objCreate("ADODB.Recordset")
    $objRecordSet               = $commandObj.Execute
    
    If($objRecordSet.RecordCount <> "") Then        
        ;------------------------------------------------------------------------------
        ; Loop through the record set
        ;------------------------------------------------------------------------------ 
        $objRecordSet.MoveFirst
        While Not $objRecordSet.EOF
            If $objectsFoundCount > 0 Then
                $objectsFoundNames  = $objectsFoundNames & @LF & $objRecordSet.Fields("distinguishedName").Value
            Else 
                $objectsFoundNames  = $objRecordSet.Fields("distinguishedName").Value
            EndIf
            
            $objRecordSet.MoveNext
            $objectsFoundCount= $objectsFoundCount+1
        WEnd

        If $objectsFoundCount > 0 Then
            return $objectsFoundNames
        Else
            return 0;
        EndIf
    Else
        return 0;
    EndIf
EndFunc

;------------------------------------------------------------------------------
;Reverse the order of all the OUs 
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; DC=com,DC=domain,OU=Service Groups,OU=IT Shop
; 
; We do this so we can do an easy alphabetical sort
;
; At this time ADO/ADSI doesn't support ORDER BY for
; organizational units
;------------------------------------------------------------------------------ 
Func returnReversedOU($ou)
    $subOUArray = StringSplit($ou, $ouSeparator2);Changer le séparateur en \
    $reversedOU = ""
    For $i = (UBound($subOUArray) - 1 ) To 1 Step -1 
        If $i = (UBound($subOUArray) -  1 ) Then
            $reversedOU = $reversedOU & $subOUArray[$i]
        Else
            $reversedOU = $reversedOU & $ouSeparator & $subOUArray[$i]
        EndIf
    Next
    return $reversedOU
EndFunc


;------------------------------------------------------------------------------
; Returns the friendly object name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; IT Shop
;------------------------------------------------------------------------------ 
Func returnFriendlyName($dn)
    return StringMid($dn, StringInStr($dn, "=")+1, StringInStr($dn, $ouSeparator)-(StringInStr($dn, "=")+1))
EndFunc

;------------------------------------------------------------------------------
; Returns the parent OU name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnParentOU($fullOU)
    return StringRight($fullOU, ( StringLen($fullOU)-StringInStr($fullOU, $ouSeparator) ) )
EndFunc

;------------------------------------------------------------------------------
; Updates the progress bar to the passed percentage
;------------------------------------------------------------------------------ 
Func UpdateProgressBar($percentage)
    GuiCtrlSetData($progressBar, $percentage)
EndFunc

;------------------------------------------------------------------------------
; Replaces the Progress Text control with supplied text
;------------------------------------------------------------------------------ 
Func UpdateProgressText($text) 
    GUICtrlSetData($progressText, $text)
EndFunc

;------------------------------------------------------------------------------
; Will return the current computername of the system running this script
;------------------------------------------------------------------------------ 
Func returnComputerName()
    $networkObj         = ObjCreate("WScript.Network")
    $computerName       = $networkObj.ComputerName
    return $computerName
EndFunc

;------------------------------------------------------------------------------
; Returns the full OU name from a DN record:
;
; Example:
;
; The DN:
; CN=Paula,OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnFullOUfromDN($dn)
    If $dn <> "0" Then
        return StringRight($dn, StringLen($dn)-StringInStr($dn, $ouIdentifier)+1)
    Else
        return 0
    EndIf
EndFunc
Edited by BoogY

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

Actualy i managed to do it... but i got another problem now.

When i click in the treeView the ou i need a variable to get its value but in this form

OU=Dsys,OU=Workstations,DC=microsoft,DC=com

so i can put'it in the functione to add the computer to the domain and in the selected OU.

I can get the variable with this :

$selectedOU = $treeIDArray[GUICtrlRead($defaultTreeView)]
GUICtrlSetData($txtOUPath,$selectedOU)

But it return a path like =

\Dsys\Workstations\microsoft\com

how can i change'it back in OU=Dsys,OU=Workstations,DC=microsoft,DC=com

Here is my code :

Ant thank you verymuch for your help :D thats rely cool.

#NoTrayIcon
#include <GUIConstants.au3>
#include <EditConstants.au3>
#include <adfunctions.au3>
#include <TreeViewConstants.au3>
#Include <Array.au3>

;------------------------------------------------------------------------------
; Domain details
;
; Change these three lines to match your enviroment
;------------------------------------------------------------------------------
$adDefaultContext   = "DOMAIN"
$adDomainController = "DOMAIN"
$adDomain       = "DOMAINNAME"

;------------------------------------------------------------------------------
; Username and password
;
; If you wish to be prompted for these values instead of hardcoding them
; here you may leave these blank.
;------------------------------------------------------------------------------
$adUsername     = IniRead(@ScriptDir & "\config.ini", "user", "username", "zsibni")
$adPassword     = IniRead(@ScriptDir & "\config.ini", "pwd", "pwd", "No Password")

;------------------------------------------------------------------------------
; Active Directory Constants
;------------------------------------------------------------------------------
Const $ldapConnectionString     = "LDAP://" & $adDomainController & "/" & $adDefaultContext
Const $ouIdentifier     = "OU="
Const $cnIdentifier     = "CN="
Const $ouSeparator      = ","
Const $ouSeparator2     = "\"


;------------------------------------------------------------------------------
; Prompt for the username if it is not hardcoded above
;------------------------------------------------------------------------------
If $adUsername = "" Then
    $adUsername     = InputBox("Input username", "Please enter the username of the account you wish to use to " & _
                    "join the domain. This should be just the username." & @LF & @LF & _
                    "Example:" & @LF & "jdoe")
    If @error Then 
        MsgBox(0, "Error with username - " & @error, "There was an error proccessing your username." & @LF & @LF & _
                "The username I received was:" & @LF & _
                $adUsername & @LF & @LF & _
                "Please restart this application and try again. If this problem persists you can try" & _
                "hard coding this information into this program by editing the source file.")
        Exit(900)
    EndIf
EndIf

;------------------------------------------------------------------------------
; Prompt for the password if it is not hardcoded above
;------------------------------------------------------------------------------
If $adPassword = "" Then
    $adPassword = InputBox("Input password","Please enter the password:",'','*')
    If @error Then 
        MsgBox(0,"Error with password - " & @error, "There was an error proccessing your password." & @LF & @LF & _
                "Please restart this application and try again. If this problem persists you can try" & _
                "hard coding this information into this program by editing the source file.")
        Exit(901)
    EndIf
EndIf

;------------------------------------------------------------------------------
; Initiate our ADO connection to Active Directory
;------------------------------------------------------------------------------
$connObj = objCreate("ADODB.Connection")
$connObj.Provider = "ADsDSOObject"
$connObj.ConnectionTimeout = "1"
$connObj.Open("Active Directory Provider", $adDomain & "\" & $adUsername, $adPassword)

;------------------------------------------------------------------------------
; Find and store the computer name of the system running this program
;------------------------------------------------------------------------------
$computername   = returnComputerName()

#Region ### START Koda GUI section ### Form=E:\PERSO\Scripts\MON PROJET\ADACV_un-join\JoinDomain.kxf
$frmJoinDomain = GUICreate("Join Domain ADACV", 601, 403, 611, 217)
$txtTFS = GUICtrlCreateInput("", 304, 32, 121, 21)
$lblTFS = GUICtrlCreateLabel("TFS :", 272, 32, 30, 17)
$btnJoinDomain = GUICtrlCreateButton("Join Domain", 504, 8, 89, 25, 0)
$lblDomainUser = GUICtrlCreateLabel("Domain User", 24, 8, 65, 17)
$txtDomainPasswd = GUICtrlCreateInput("", 96, 32, 121, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
$txtDomainUser = GUICtrlCreateInput("" & @UserName &"", 96, 8, 121, 21)
$lblDomainPasswd = GUICtrlCreateLabel("Domain Passwd", 8, 32, 80, 17)
$txtLocalPasswd = GUICtrlCreateInput("", 304, 8, 121, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
$Label1 = GUICtrlCreateLabel("Local Passwd", 224, 8, 70, 17)
$progressText = GUICtrlCreateLabel("Join ADACV Domain", 8, 104, 589, 57)
$defaultTreeView = GUICtrlCreateTreeView(8, 160, 585, 209)
$progressBar = GUICtrlCreateProgress(8, 376, 585, 17)
$txtOUPath = GUICtrlCreateInput("", 8, 80, 585, 21)
$lblOUPath = GUICtrlCreateLabel("OU Path :", 8, 56, 51, 17)
$btnAddOU = GUICtrlCreateButton("Ajouter OU", 504, 40, 89, 25, 0)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

;------------------------------------------------------------------------------
; Query for all organizational units
;------------------------------------------------------------------------------
$arAllOU = _ADGetAllOUs () ; get all OU's of domain
_arraysort($arAllOU)


Dim $treeIDArray[UBound($arAllOU)*2]
;------------------------------------------------------------------------------
; Return the OUs to their original format and create the TreeView Entries.
;------------------------------------------------------------------------------
$adCurrentObjectNumber = 0
For $reversedOU in $arAllOU
    If $reversedOU = "" then 
        ContinueLoop
    EndIf
    ;------------------------------------------------------------------------------
    ; Reverse the order back to the orginal format  
    ;------------------------------------------------------------------------------ 
    $ou = returnReversedOU($reversedOU)
    ;------------------------------------------------------------------------------
    ; Calculate the additional values for this OU and check to see if its
    ; parentou has a GUI TreeID
    ;------------------------------------------------------------------------------     
    $fullOU         = StringStripWS($ou, 3)         
    $friendlyOU     = returnFriendlyName($fullOU)           
    $parentFullOU   = returnParentOU($fullOU)           
    $parentTreeID   = _ArraySearch($treeIDArray, $parentFullOU)
    ;------------------------------------------------------------------------------
    ; Check if this OU has a parent. If it does make this TreeView item a child
    ; of that parent.
    ;------------------------------------------------------------------------------
    If ( $parentTreeID <> "-1" ) Then   
        $treeID = GUICtrlCreateTreeViewItem ($friendlyOU, $parentTreeID)
    Else    
        $treeID = GUICtrlCreateTreeViewItem ($friendlyOU, $defaultTreeView)
    EndIf   
    ;------------------------------------------------------------------------------
    ; The returned $treeID is sequential. We can use this to cheat and emulate
    ; a hashtable.
    ;------------------------------------------------------------------------------
    $treeIDArray[$treeID] = $fullOU
    UpdateProgressBar(($adCurrentObjectNumber / UBound($arAllOU)) * 100)
    UpdateProgressText("Currently querying " & $friendlyOU)
    $adCurrentObjectNumber = $adCurrentObjectNumber + 1
Next
;------------------------------------------------------------------------------
; Query is complete, update Progress Text
;------------------------------------------------------------------------------
UpdateProgressText("Veuillez sélectionner une OU pour ajouter la machine.")

;------------------------------------------------------------------------------
; Check and see if this computername is already present in AD
;------------------------------------------------------------------------------
$computersCN = returnObjectDN($computername, "computer")
If $computersCN <> "0" Then
    $computersOU = returnFullOUfromDN($computersCN)
    UpdateProgressText("Found this computer (" & $computername & ") in the " & _
                returnFriendlyName($computersOU) & " - This has been selected " & _
                "for you below.")
    GuiCtrlSetState(_ArraySearch($treeIDArray, $computersOU), $GUI_FOCUS)
EndIf


While 1
    $msg = GUIGetMsg()
    Select
        Case $msg = $GUI_EVENT_CLOSE
            Exit
            
        Case $msg = $btnAddOU
            $selectedOU = $treeIDArray[GUICtrlRead($defaultTreeView)]
            GUICtrlSetData($txtOUPath,$selectedOU)
            
        Case $msg = $btnJoinDomain
            $selectedOU = returnFullOUfromDN($treeIDArray[GUICtrlRead($defaultTreeView)])
;~          $LocAdmPwd = GUICtrlRead($txtLocalPasswd)
;~          $CompName = GUICtrlRead($txtTFS)
;~          $DomUser = GUICtrlRead($txtDomainUser)
;~          $DomPwd = GUICtrlRead($txtDomainPasswd)
;~          $OUPath = $selectedOU
;~          If $CompName = "" Then
;~              MsgBox(0,"ERREUR","Pas de numéro TFS")
;~          Else
;~              JoinADACV($LocAdmPwd,$CompName,$DomUser,$DomPwd,$OUPath)
;~          EndIf
    EndSelect
WEnd

;------------------------------------------------------------------------------
; Join the computer to the domain and OU
;------------------------------------------------------------------------------ 
Func JoinADACV($LocAdmPwd,$CompName,$DomUser,$DomPwd,$OUPath)
    $cmd = RunWait(@ComSpec & " /c \\Nstockpack\packages$\Tools\netdom.exe join " & $CompName & " /Domain:adacv /OU:"& $OUPath &"/UserO:" & $CompName & "\xbrtfs /PasswordO:" & $LocAdmPwd & " /UserD:"& $DomUser &" /PasswordD:"& $DomPwd &" /reboot")
    If @error Then
        MsgBox(0,"ERREUR","Le pc n'as pas été ajouté au domain ADACV" & @CRLF & "Erreur : " & @error)
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    Else
        MsgBox(0,"Succès","Le pc " & $CompName & " a été ajouté au domain")
        GUICtrlSetData($lblMessage,"Erreur d'ajout dans le domain")
    EndIf
EndFunc

;------------------------------------------------------------------------------
; Searches AD via ADO for the DN of an object
; 
;
; If the DN is found then it is returned.
;
; If no match is found then 0 is returned
; 
;
; If more then one match is found then they are returned
; as a single string, separated by linebreaks.
;
; The second paramter dictates the object type to
; search for. It can either by user, computer, or
; organizationalunit. Alternatively it can be an objectclass
; your AD structure supports.
; 
;------------------------------------------------------------------------------ 
Func returnObjectDN($objectName, $objectClass)
    $objectsFoundCount          = 0
    Dim $objectsFoundNames
    
    ;------------------------------------------------------------------------------
    ; Create the ADO object and execute the search
    ;------------------------------------------------------------------------------     
    $commandObj             = objCreate("ADODB.Command")
    $commandObj.ActiveConnection        = $connObj
    $commandObj.CommandText         = "SELECT distinguishedName FROM '" & $ldapConnectionString & "' " & _
                          "WHERE objectClass='" & $objectClass & "' AND name ='" & $objectName & "'"  
    $commandObj.Properties("Page Size")     = 10000
    $commandObj.Properties("Cache Results") = True
    $commandObj.Properties("SearchScope")   = 2

    $objRecordSet               = objCreate("ADODB.Recordset")
    $objRecordSet               = $commandObj.Execute
    
    If($objRecordSet.RecordCount <> "") Then        
        ;------------------------------------------------------------------------------
        ; Loop through the record set
        ;------------------------------------------------------------------------------ 
        $objRecordSet.MoveFirst
        While Not $objRecordSet.EOF
            If $objectsFoundCount > 0 Then
                $objectsFoundNames  = $objectsFoundNames & @LF & $objRecordSet.Fields("distinguishedName").Value
            Else 
                $objectsFoundNames  = $objRecordSet.Fields("distinguishedName").Value
            EndIf
            
            $objRecordSet.MoveNext
            $objectsFoundCount= $objectsFoundCount+1
        WEnd

        If $objectsFoundCount > 0 Then
            return $objectsFoundNames
        Else
            return 0;
        EndIf
    Else
        return 0;
    EndIf
EndFunc

;------------------------------------------------------------------------------
;Reverse the order of all the OUs 
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; DC=com,DC=domain,OU=Service Groups,OU=IT Shop
; 
; We do this so we can do an easy alphabetical sort
;
; At this time ADO/ADSI doesn't support ORDER BY for
; organizational units
;------------------------------------------------------------------------------ 
Func returnReversedOU($ou)
    $subOUArray = StringSplit($ou, $ouSeparator2);Changer le séparateur en \
    $reversedOU = ""
    For $i = (UBound($subOUArray) - 1 ) To 1 Step -1 
        If $i = (UBound($subOUArray) -  1 ) Then
            $reversedOU = $reversedOU & $subOUArray[$i]
        Else
            $reversedOU = $reversedOU & $ouSeparator & $subOUArray[$i]
        EndIf
    Next
    return $reversedOU
EndFunc


;------------------------------------------------------------------------------
; Returns the friendly object name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; IT Shop
;------------------------------------------------------------------------------ 
Func returnFriendlyName($dn)
    return StringMid($dn, StringInStr($dn, "=")+1, StringInStr($dn, $ouSeparator)-(StringInStr($dn, "=")+1))
EndFunc

;------------------------------------------------------------------------------
; Returns the parent OU name:
;
; Example:
;
; The full OU of:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnParentOU($fullOU)
    return StringRight($fullOU, ( StringLen($fullOU)-StringInStr($fullOU, $ouSeparator) ) )
EndFunc

;------------------------------------------------------------------------------
; Updates the progress bar to the passed percentage
;------------------------------------------------------------------------------ 
Func UpdateProgressBar($percentage)
    GuiCtrlSetData($progressBar, $percentage)
EndFunc

;------------------------------------------------------------------------------
; Replaces the Progress Text control with supplied text
;------------------------------------------------------------------------------ 
Func UpdateProgressText($text) 
    GUICtrlSetData($progressText, $text)
EndFunc

;------------------------------------------------------------------------------
; Will return the current computername of the system running this script
;------------------------------------------------------------------------------ 
Func returnComputerName()
    $networkObj         = ObjCreate("WScript.Network")
    $computerName       = $networkObj.ComputerName
    return $computerName
EndFunc

;------------------------------------------------------------------------------
; Returns the full OU name from a DN record:
;
; Example:
;
; The DN:
; CN=Paula,OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;
; Is returned as:
; OU=IT Shop,OU=Service Groups,DC=domain,DC=com
;------------------------------------------------------------------------------ 
Func returnFullOUfromDN($dn)
    If $dn <> "0" Then
        return StringRight($dn, StringLen($dn)-StringInStr($dn, $ouIdentifier)+1)
    Else
        return 0
    EndIf
EndFunc

Hi,

you know your domain suffix, e.g. microsoft.com.

So do a Stringsplit ($selectedOU , "\") and put your string with a loop together.

in this case, the last two array elements are the dc= elements (microsoft.com); the other must be ou=.

If you have domain suffix mydomain.domain.local the last three elements of your array are the dc= elements.

;-))

Stefan

Edited by 99ojo

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0