Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a computer to a domain programmatically (using .NET)?

Tags:

.net

windows

dns

I need to write a program or script that does a few things with (or to) a server after a Windows install. Among those is adding the server to a domain.

Is there a way to do this programmatically or using a script command?

like image 217
Andrew J. Brehm Avatar asked Oct 14 '22 04:10

Andrew J. Brehm


2 Answers

If you want to do it from the Domain Controller:

Source: net computer \\computername /add

If you want to do it from the workstation:

Source: NETDOM JOIN /DOMAIN:[DOMAINNAME] /USERD:[USERNAME] /PASSWORDD:[PASSWORD]

like image 122
Jaxidian Avatar answered Oct 17 '22 01:10

Jaxidian


It is not easy if you write a program, but it is possible and you can find corresponding code examples.

First of all you should create computer account in the domain. To do this you can use NetUserAdd function. The corresponding code example you will find under http://msdn.microsoft.com/en-us/library/aa370254%28VS.85%29.aspx. If you have a new computer account already created in Active Directory (in any way) in the corresponding destination OU you can skip the step. You must only understand, which password have this account (the password will be constructed based on the computer name, see code example for details).

Next you should get SID of Domain to which you add computer, and at the end you should use so-named LSA API to make all work locally with respect of LsaSetTrustedDomainInformation. The corresponding code example you can find in http://support.microsoft.com/kb/145697.

If you do have to create a omputer account in the domain, be careful that you all time works with the same domain controller. Otherwise you can have small problem till the new account will be replicated to the next domain controller which you use (a small waiting loop with retries can be sufficient).

P.S. If you receive some problems with the implementation you can ask me additional question about this subject.

like image 44
Oleg Avatar answered Oct 16 '22 23:10

Oleg