Create and delete users using windows scripting host (jscript)

Today I play a little with ADSI (Active Directory Service Interfaces). It is a set of classes, available in Windows XP that allows you to change configuration settings and manage system objects, such as users, groups, security permissions and so on. With ADSI you can even change IIS configuration settings.

The following examples demonstrate how to automatize daily administrators' tasks: creating and deleting user accounts and changing users' membership.

Create user account in Administrators group

// Get computer name
var variables = WScript.CreateObject('WScript.Shell').Environment('Process');
var computer = variables('computername').toLowerCase();

// Specify user name
var username = 'Tom';

var account = null;
try {
	// Get account, if it is cannot be found, this line throws an exception
	account = GetObject('WinNT://' + computer + '/' + username + ',user');
} catch (e) {
	// Of course there are a number of reasons for exception, but let's
	// assume everything is OK and user just does not exist.
	WScript.echo('User account is not found. Creating...');
}

// Create account
var accounts = GetObject('WinNT://' + computer + ',Computer');
account = accounts.Create('user', username);
account.SetPassword('secret');
account.SetInfo();

// Setup membership
var usersGroup = GetObject('WinNT://' + computer + '/Administrators,group');
usersGroup.Add('WinNT://' + computer + '/' + username + ',user');

WScript.echo('Done.');

Delete user account

// Get computer name
var variables = WScript.CreateObject('WScript.Shell').Environment('Process');
var computer = variables('computername').toLowerCase();

// Specify user name
var username = 'Tom';

var account = null;
try {
	// Get account, if it is cannot be found, this line throws an exception
	account = GetObject('WinNT://' + computer + '/' + username + ',user');
} catch (e) {
	// Of course there are a number of reasons for exception, but let's
	// assume everything is OK and user just does not exist.
	WScript.echo('User account is not found. Nothing to do, exiting...');
	WScript.quit();
}

// Delete account
var accounts = GetObject('WinNT://' + computer + ',Computer');
accounts.Delete('user', username);
WScript.echo('Done.');