The Tao of Jace

November 12, 2008

Active Directory Stuff

Filed under: Archive — site admin @ 5:01 pm

At the new job, I’m running a small domain for field users. At the old job, EDS had a nifty script that would put the user’s computer name into the office field. I decided to recreate that today because I’m needing to back up computers and I don’t have an index of who’s using which computers readily available. For any who might be interested, here’s the code:

// ComputerName.js - Set the computer name into the Office field in
//	Active Directory
// Author - Jace Gregg
// Version 1.0 - 12 November 2008
// -----------------------------------------------------------------
var cTITLE = "Dawson Scripting: Computer Name";

try {
	var username = ParseEnvironStrings("%username%");
	var computername = ParseEnvironStrings("%computername%")
	var cn = "";

	var conn = WScript.CreateObject("ADODB.Connection");
	var cmd = WScript.CreateObject("ADODB.Command");

	conn.Open("Provider=ADsDSOObject;");
	cmd.ActiveConnection = conn;

	cmd.CommandText = "<ldap ://dc=dawsonfield,dc=local>;(&(objectCategory=User)(samAccountName=" + username + "));samAccountName,cn;subtree";

	var rs = cmd.Execute();

	if(rs.RecordCount == 0) {
		msgbox("sAMAccountName: " + username + " does not exist.");
	}
	else {
		cn = rs.Fields("cn");
		msgbox(cn);
	}

	var objUser = GetObject("LDAP://cn=" + cn + ",ou=FieldUsers,dc=dawsonfield,dc=local");

	objUser.Put("physicalDeliveryOfficeName", computername);
	objUser.SetInfo(); 

	rs.close();
	conn.close();
}
catch(e) {
	msgbox("Error " +  e.number + "\n\n" + e.description + "\nCould not update computer name.");
}
function msgbox(message, title) {
	if(title == null) {
		title = cTITLE
	}
	var objWSH = WScript.CreateObject("Wscript.Shell");
	objWSH.Popup (message, 10, title);
}

function ParseEnvironStrings(strInput) {
	var WshShell = WScript.CreateObject("WScript.Shell");

	return WshShell.ExpandEnvironmentStrings(strInput);
}

Save it as a .js file and run it as a startup script with group policy or some other way. Feel free to use this in your own projects/work. Took me an hour to figure it out, so I imagine someone else might need it too.

Powered by WordPress