Reset terminal services profile information in Active Directory

If you have a widely distributed network environment and many centrally located terminal servers, it is often desirable to regulate users' terminal server profile information by using group policies. In that way, you can avoid unintended delays caused by access to remote directories.

Microsoft provides group policies Set path for TS Roaming Profiles and TS User Home Directory  for that purpose. If you decide to take those policies in use, you may then be interested in a central clean-up in Active Directory by resetting existing terminal services profile information.

The perl script below can do this job for you:

# Script to reset terminal services profile information in Active Directory
# requires dsquery tool and perl with Win32::API
use strict;
use warnings;
use Win32;
use Win32::OLE qw (in);
use Win32::API;
Win32::API->Import( "user32",  "BOOL OemToCharBuff(LPCTSTR lpszSrc, LPTSTR lpszDst, DWORD cchDstLength)");
my ( $obj, $rootdn, $userdn );
# Get default naming context
$obj = Win32::OLE->GetObject("LDAP://rootDSE");
$rootdn = $obj->Get("defaultNamingContext");
# Command to list user DNs, We use dsquery with no limits, customize it according to your needs
open USERS, "dsquery user -limit 0 | " or die $!;
while (<USERS>)
 ($userdn) = ($_ =~ /\"(.*)\"/); # remove leading and trailing " s
 OemToCharBuff($userdn, $userdn, length($userdn)); # ANSI to OEM conversion
 $obj = Win32::OLE->GetObject ("LDAP://$userdn");
 $obj || print STDERR "Object $userdn does not exist.\n" || next;
 my $username = $obj->{"Name"};
 my $tshome = $obj->{"TerminalServicesHomeDirectory"};
 my $tsdrive = $obj->{"TerminalServicesHomeDrive"};
 my $tspath = $obj->{"TerminalServicesProfilePath"};
 # Skip if no related information is available
 next if  $tshome eq "" and  $tsdrive eq "" and $tspath eq "";
 # reset AD attributes
 $obj->{TerminalServicesHomeDirectory} = "";
 $obj->{TerminalServicesHomeDrive} = "";
 $obj->{TerminalServicesProfilePath} = "";
 # Log results to STDOUT
 print "$username (tshome=$tshome, tsdrive=$tsdrive,tspath=$tspath) is reset.\n";