Question

Create a local profile on Windows XP machine for a Domain user.

Asked by: PilzberryFroBoy

I have been tasked with rolling out several hundred new computers.  

The computers will all be imaged and will not be joined to the domain until they are physically on the clients desk.  The trick is, I need to take some data from their local profile on their current machine, and migrate it to the new workstation.  

So, I created a script to pull their data, and store it to a server until the new computer is added to the domain, and the user logs on with their Domain Account.
I read the solution here: http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23091801.html, but I'd need the user's ID and Password.  As it stands, an admin still has to logon when the new computer is booted up, so it can be added to the domain, and computer name changed.

I tried a solution where the registry keys that go along with the user's SID are created, but when the user logs on, Windows just overwrites the values with new information, and creates a profile folder called USERID123.DOMAINNAME. So, I tried modifying the folder path to create a profile folder called USERID123.DOMAINNAME, and again, it overwrote the registry keys and created a profile folder called USERID123... Yes, I wanted to slap myself multiple times about the face and neck, but I thought I might get canned for that.  So I'm here asking for your help.  I have no cookies though, sorry.

This is a working function I scraped together to try the above note.

Function createUserProfile(userSID, userID)
Const HKLM = &H80000002
'userSID = "S-1-5-21-12345678-1234567890-1234567890-12345"
'userID = "USERID123"
strKey = "Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
strComputer = "."

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strUserKeyPath = strKey & "\" & userSID
oReg.CreateKey HKLM, strUserKeyPath

strUserPathKeyName = "ProfileImagePath"
strUserPathValue = "%SystemDrive%\Documents and Settings\" & userID
oReg.SetExpandedStringValue HKLM,strUserKeyPath,strUserPathKeyName,strUserPathValue

strUserFlagKeyName = "Flags"
strUserFlagValue = 1
oReg.SetDWORDValue HKLM,strUserKeyPath,strUserFlagKeyName,strUserFlagValue
Set oReg = Nothing

Set objFSO = CreateObject("Scripting.FileSystemObject")
userFolderPath = "C:\Documents and Settings\" & userID
objFSO.CreateFolder userFolderPath
objFSO.CreateFolder userFolderpath & "\Cookies"
objFSO.CreateFolder userFolderpath & "\Desktop"
objFSO.CreateFolder userFolderpath & "\Favorites"
objFSO.CreateFolder userFolderpath & "\My Documents"
objFSO.CreateFolder userFolderpath & "\Start Menu"
Set objFSO = Nothing
createUserProfile = "Successfully created profile for " & userID
End Function

What I'm really getting at is, I want to create the a local profile for a domain user before they ever log on, and without having to use their ID/Password credentials.

Anyone?  Anyone?  BUELLER?

If you read all that, thank you!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-10 at 17:47:44ID24218334
Topic

VB Script

Participating Experts
2
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. CreateObject(
    Fellow developers, I have an ASP driven app that until yesterday was running on a single Windows 98 PC running PWS. I have migrated to a Windows 2000 Server (SP3) running IIS. I even installed MDAC 2.7. The website works except for a very important piece. I seem to have ...
  2. HKLM\ RunOnce does not run until login
    I have enter the command c:\firstrun.cmd into the HKLM\Software\Microsoft\Windows\CurrectVersion\Runonce key and the program only runs after loggin in I want it to run before login any ideas
  3. objFSO
    i have two different server one is a webserver and the other is a storage server, in my web page using vbscript, i was trying to read the files inside the storage server but i keep getting invalid directory or file not found this is the way i did it. could you tell me how to ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: RobSampsonPosted on 2009-03-10 at 22:46:40ID: 23854181

I do the same thing when I change PCs, and currently, we back up the profile on the old pc, get them to log into the new computer (which creates their profile with the right folder name against the right SID), then we reboot, log in as admin, and copy their old profile data into
c:\documents and settings\<username>

I would love to be able to copy the profile back into the new computer without having them log in first, and then have them log in and not have a new folder created.  Your function looks interesting...I'll have to test it....you can't be far off with the ProfileList keys.....

I looked at MoveUser.exe but that's for account to account moving.....

Someone else may know how to do this easily, but I'll look into it in the meantime...

Regards,

Rob.

 

by: chakkoPosted on 2009-03-10 at 23:07:25ID: 23854258

You might try to convert the user to a Roaming Profile first.  Roaming profile is stored on a server share.

When they logon to the new machine it will get their profile from the Server.  After the user has logged on/off and everything seems OK, then you can remove the Profile Path (In AD Users -> Properties -> Profile tab) - empty the box.

After the user logs on/off some more, then the profile should be running completely from the local hard drive.


 

by: RobSampsonPosted on 2009-03-10 at 23:15:05ID: 23854292

Thinking about it (but not being able to test it today)....if you use the following code to obtain the SID for an AD account, you might be able to export the correct ProfileList key when you back up the profile, then just import the reg after you join the computer to the domain.  Then you might be able to copy the user profile folder straight over.....

I will try to test that soon.....

Regards,

Rob.

strUsername = InputBox("Enter the username you wish to find the SID for:", "Username", strUsername)
strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adsPath")
If Left(strUserADsPath, 7) = "LDAP://" Then
	Set objUser = GetObject(strUserADsPath)
	arrSid = objUser.objectSid
	strSidHex = OctetToHexStr(arrSid)
	strSidDec = HexStrToDecStr(strSidHex)
	
	InputBox "The SID for " & objUser.samAccountName & " is in the variable strSidDec and is below:", "Title", strSidDec
Else
	MsgBox "Could not find adsPath for " & strUsername
End If
 
'Working VBScript Active Directory Binary SID conversion to String SID
' Source: http://forums.techarena.in/showthread.php?t=588078
'Function to convert OctetString (byte array) to Hex string.
Function OctetToHexStr(arrbytOctet)
Dim k
OctetToHexStr = ""
For k = 1 To Lenb(arrbytOctet)
OctetToHexStr = OctetToHexStr & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
Next
End Function
 
Function HexStrToDecStr(strSid)
' Function to convert Hex string Sid to Decimal string (SDDL) Sid.
 
 
' SID anatomy:
' Byte Position
' 0 : SID Structure Revision Level (SRL)
' 1 : Number of Subauthority/Relative Identifier
' 2-7 : Identifier Authority Value (IAV) [48 bits]
' 8-x : Variable number of Subauthority or Relative Identifier (RID) [32 bits]
'
' Example:
'
' <Domain/Machine>\Administrator
' Pos : 0 | 1 | 2 3 4 5 6 7 | 8 9 10 11 | 12 13 14 15 | 16 17 18 19 | 20 21 22 23 | 24 25 26 27
' Value: 01 | 05 | 00 00 00 00 00 05 | 15 00 00 00 | 06 4E 7D 7F | 11 57 56 7A | 04 11 C5 20 | F4 01 00 00
' str : S- 1 | | -5 | -21 | -2138918406 | -2052478737 | -549785860 | -500
 
 
Const BYTES_IN_32BITS = 4
Const SRL_BYTE = 0
Const IAV_START_BYTE = 2
Const IAV_END_BYTE = 7
Const RID_START_BYTE = 8
Const MSB = 3 'Most significant byte
Const LSB = 0 'Least significant byte
 
 
Dim arrbytSid, lngTemp, base, offset, i
 
 
ReDim arrbytSid(Len(strSid)/2 - 1)
 
 
' Convert hex string into integer Array
For i = 0 To UBound(arrbytSid)
      arrbytSid(i) = CInt("&H" & Mid(strSid, 2 * i + 1, 2))
Next
 
 
' Add SRL number
HexStrToDecStr = "S-" & arrbytSid(SRL_BYTE)
 
 
' Add Identifier Authority Value
lngTemp = 0
For i = IAV_START_BYTE To IAV_END_BYTE
      lngTemp = lngTemp * 256 + arrbytSid(i)
Next
HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
 
 
' Add a variable number of 32-bit subauthority or
' relative identifier (RID) values.
' Bytes are in reverse significant order.
' i.e. HEX 01 02 03 04 => HEX 04 03 02 01
' = (((0 * 256 + 04) * 256 + 03) * 256 + 02) * 256 + 01
' = DEC 67305985
For base = RID_START_BYTE To UBound(arrbytSid) Step BYTES_IN_32BITS
      lngTemp = 0
      For offset = MSB to LSB Step -1
            lngTemp = lngTemp * 256 + arrbytSid(base + offset)
      Next
      HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
Next
End Function ' HexStrToDecStr
 
Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '				It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '				For example, if you are searching based on the user account name, strSearchField
      '				would be "samAccountName", and strObjectToGet would be that speicific account name,
      '				such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '	strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '				the home folder path, as defined by the AD, for a specific user, this would be
      '				"homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '				user and get your own parameters from them, then use "ADsPath" as a return string,
      '				then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal
 
End Function

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:

Select allOpen in new window

 

by: PilzberryFroBoyPosted on 2009-03-11 at 05:37:40ID: 23856345

Hey guys, thanks for the responses!

@chakko, that's an interesting idea.  I'll look into it today, and see if that will be an option.  I'm not sure how much control I have over AD objects yet.

@Rob, thank you for your reply.  I had not considered exporting the ProfileList keys yet.  I'll explore this more once I get into the office.

One thing I did notice though, is that HKEY_USERS is also populated with a SID_KEY and a SID_KEY_Classes when a "profile" is created.  I am also going to look into creating this hive of keys also. I suspect that once a "shell" is created in the registry, Windows will be able to add/update any subkeys it needs, but it's just going to be finding out which keys it must see as present before it will do that.

Anyhow, totally appreciate the responses.  I'm all giddy with excitement now...  That may not have been the right word.  :)

 

by: PilzberryFroBoyPosted on 2009-03-11 at 11:33:03ID: 23860611

Just so no one spends any more time trying to solve this, I have a working solution, and I will post it this evening.

@chakko, that was a great idea, it would have worked if I had sufficient rights to a User object in Active Directory, but I have almost no rights to modify.  

@Rob, your script in conjunction with my script and some (ok quite a bit more) extra script, I was able to get a pretty decent solution together.  I'm hopeful that someone may be able to streamline it.

Thanks!

 

by: RobSampsonPosted on 2009-03-11 at 12:44:02ID: 23861472

>>  I'm hopeful that someone may be able to streamline it.

Sure, go ahead and post your solution and I'll definately give it a shot!  I hope it works well, because it would certainly streamline my 120 PC rollout going on in a couple of months.....

Regards,

Rob.

 

by: RobSampsonPosted on 2009-03-16 at 13:10:30ID: 23901857

Hey mate, any luck on this?

Regards,

Rob.

 

by: RobSampsonPosted on 2009-03-27 at 21:48:26ID: 24007273

Hey guys,

Well I finally had a chance to test this, and it turns out that the method of backing up the
HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\<SID>
key, importing that to a new computer, and *then* copying C:\Documents and Settings\<username> to the new computer does work!  You can then log onto the new computer without it creating a new <username>.<domain> profile path.

So I'm writing an export script, and an import script that will automate this task for the most part, which I will post here in the next few days.

Regards,

Rob.

 

by: RobSampsonPosted on 2009-04-06 at 23:15:27ID: 24084314

Ha ha, by "next few days", I guess I meant week or so....

Watch this space....next week I will post it.

Rob.

 

by: PilzberryFroBoyPosted on 2009-04-16 at 22:52:04ID: 31556567

So, I am so, so, sorry about not replying earlier.  I had a change of job in mid project.

The short answer to creating a profile for a user before they log on is 1) create a reg key with the user's SID, 2) create a sub key with the path to %systemroot%\Documents and Settings\[Users ID] for their profile path, then 3) copy the Default User profile from C:\Documents and Settings\Default User to C:\Documents and Settings\[UserID].  Now, if you migrate their profile folders (we only did Desktop, Favorites, My Documents, and My Recent Documents) to a repository, you can import it back to the new location created above.

I'm not sure how much space I have here, but I created an HTA file that does the listed process.  Copy and paste this code into a new text file, save it as Backup.HTA, and run.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>User Migration</title>
    <hta:application id="BackupAccounts" applicationname="Command Line Agruments" singleinstance="yes">

<style type="text/css">
.funcHeader {
      text-decoration: none;
}
.funcHeader:hover {
    text-decoration: underline;
    color: black;
    cursor: hand;
}

.actionSelect {
    position: absolute;
    top: 0px;
    left: 0px;
    border-style: solid;
    border-width: 1px;
    border-color: black;
}

.tabHeaderSelectedCell {
    font-weight: bold;
    border-left-color: black;
    color: black;
    border-top-style: solid;
    border-top-color: black;
    border-right-style: solid;
    border-left-style: solid;
    background-color: #778899;
    border-right-color: black;
    width: 33%;
}
.tabHeaderSelected {
    font-weight: bold;
    vertical-align: middle;
    text-align: center;
    background-color: #778899;

}
.tabHeaderNotSelectedCell {
    border-right: black thin solid;
    border-top: black thin solid;
    border-left: black thin solid;
    color: black;
    background-color: #998877;
    border-bottom-color: black;
    border-bottom-style: solid;
    width: 31%;
}
.tabHeaderNotSelected {
    font-weight: normal;
    vertical-align: middle;
    text-align: center;
    background-color: #998877;
}

.tabHeaderSelected:hover {
   
}
.tabHeaderNotSelected:hover {
    background-color: #998877;
    cursor: hand;
    color:#FFFFFF;
}

.tabNotVisible {
    display:none;
}

.tabVisible {
    display:block;
}

a {
      color:#FFFFFF;
      text-decoration: none;
}
a:hover {
      text-decoration: underline;
      color: white;
}
body {
      margin:0px;
      background-color:#580000; /*#F6F6F6; #CBCBCB;*/
      font-family:Arial, Helvetica, sans-serif;
      font-size:12px;
      color:#FFFFFF;
}
</style>

<SCRIPT Language="VBScript">
'http://www.w3.org/TR/CSS2/tables.html
'onclick="Msgbox(rbScope(0).value & txtAddUserID.value)"

Dim currComputer
Dim currUser
Dim vcUser
Dim lastPCPath
lastPCPath = " "

currComputer = getLocalComputerName(".")
tmpRLE = readLastEntry(4)
lastPCPath = tmpRLE(0)
'===============

'===============
Sub Window_onLoad
      arrCommands = Split(BackupAccounts.commandLine, chr(34))
      cmds = Ubound(arrCommands)
      If cmds > 2 Then
            For i = 3 to (Ubound(arrCommands) - 1) Step 2
                Select Case Split(arrCommands(i), ":")(0)
                    Case "Computer"
                        currComputerName.InnerHTML = Split(arrCommands(i), ":")(1)
                    Case "User"
                        currUserName.InnerHTML = Split(arrCommands(i), ":")(1)
                End Select
              'Msgbox arrCommands(i)
                  'testSpan.InnerHTML = testSpan.InnerHTML & "
" & arrCommands(i)
                  'document.getElementById("txtAreaMain").value = document.getElementById("txtAreaMain").value & vbcrlf & arrCommands(i)
            Next
      Else
            currComputer = getLocalComputerName(".")
            VCName.InnerHTML = currComputer
            VCLink.InnerHTML = currComputer
            Dim r
          If testPing(currComputer) = True Then
                r = Split(pingPC(currComputer), ";")
                SetStatus(r(1))
                SetIP(r(2))
                SetDomain(r(3))
                document.GetElementByID("VCBIOS").value = getBIOS(currComputer)
                VCAccounts.InnerHTML = getUsersList
            innerVal = Split(lastPCPath, "|")(0)
            If UBOUND(tmpRLE) = 0 Then
                If Not innerVal = currComputer Then
                    oldPCPath.InnerHTML = innerVal
                    oldPCPath.className = "funcHeader"
                    Call oldPCPath.attachEvent("onclick",GetRef("readLog"))
                  End If
            Else
                oldPCList = "<Select name=""optLastPC"" id=""optLastPC"" SIZE=""4"" onchange=""readLog"">"
                For i = 0 to UBOUND(tmpRLE)
                    oldPCList = oldPCList & "<Option value=""" & Split(tmpRLE(i), "|")(0) & """>" & Split(tmpRLE(i), "|")(0)
                Next
                oldPCList = oldPCList & "</Select>"
                oldPCPath.InnerHTML = oldPCList
            End If
            End If
      End If
End Sub
'===============

'===============
Function readLog
    Select Case window.event.srcElement.id
        Case "oldPCPath"
            val = oldPCPath.InnerHTML
        Case "optLastPC"
            val = window.event.srcElement.value
    End Select
   
    Dim returnValues()
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8
   
    logFileName = "log.txt"
   
    Dim arrDel()
    Dim cleanList()
    Dim newContents
    Set fso = CreateObject("Scripting.FileSystemObject")
 
    If fso.FileExists(logFileName) = True Then
        Set rFile = fso.OpenTextFile(logFileName, ForReading)
        If rFile.AtEndOfStream Then
           
        Else
            contents = rFile.ReadAll
            rFile.Close
            For each c in Split(contents, VbCrLf)
                If Len(Trim(c)) > 0 Then
                    newContents = newContents & c & VbCrLf
                End If
            Next
            arrContents = Split(newContents, vbcrlf)
            findVal = Split(Filter(arrContents, val)(0), "|")
            user = findVal(1)
            userSID = findVal(2)
            exportedTo = findVal(3)
            Set tmp = Document.getElementById(window.event.srcElement.parentElement.id)
            If tmp.children.length = 1 Then
                Set n = Document.createElement("DIV")
                n.InnerHTML = "User Exported: " & user
                n.InnerHTML = n.InnerHTML & "
User SID: " & userSID
                n.InnerHTML = n.InnerHTML & "
User Export Location: " & exportedTo
                tmp.appendChild(n)
            Else
                tmp.removeChild(tmp.lastChild)
                Set n = Document.createElement("DIV")
                n.InnerHTML = "User Exported: " & user
                n.InnerHTML = n.InnerHTML & "
User SID: " & userSID
                n.InnerHTML = n.InnerHTML & "
User Export Location: " & exportedTo
                tmp.appendChild(n)            
            End If    
        End If
    Else
   
    End If
End Function
'===============

'===============
Sub showOptions(val)
    Select Case val
        Case 0
            document.getElementById("tdAdd").style.display = ""
            document.getElementById("tdRemove").style.display = "none"
            document.getElementById("tdExport").style.display = "none"
            document.getElementById("tdImport").style.display = "none"
        Case 1
            document.getElementById("tdAdd").style.display = "none"
            document.getElementById("tdRemove").style.display = ""
            document.getElementById("tdExport").style.display = "none"
            document.getElementById("tdImport").style.display = "none"
        Case 2
            document.getElementById("tdAdd").style.display = "none"
            document.getElementById("tdRemove").style.display = "none"
            document.getElementById("tdExport").style.display = ""
            document.getElementById("tdImport").style.display = "none"
        Case 3
            document.getElementById("tdAdd").style.display = "none"
            document.getElementById("tdRemove").style.display = "none"
            document.getElementById("tdExport").style.display = "none"
            document.getElementById("tdImport").style.display = ""
            Dim oldPCs
            Set oldPCs = document.getElementById("oldPCPath")
            If oldPCs.children(0).length > 1 Then
                spanImportPCs.InnerHTML = "\\CSPTempServer\C$\" & oldPCs.children(0)(1).value
            End If
            Set oldPCs = Nothing
    End Select
End Sub
'===============

'===============
Sub hideOptions(val)
    Select Case val
        Case 0
            document.getElementById("tdAdd").style.display = "none"
        Case 1
            document.getElementById("tdRemove").style.display = "none"
        Case 2
            document.getElementById("tdExport").style.display = "none"
        Case 3
            document.getElementById("tdImport").style.display = "none"
    End Select
End Sub
'===============

'===============
Function readLastEntry(last)
    Dim returnValues()
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8
   
    logFileName = "log.txt"
   
    Dim arrDel()
    Dim cleanList()
    Dim i
    Dim newContents
    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(logFileName) = True Then
        Set rFile = fso.OpenTextFile(logFileName, ForReading)
        If rFile.AtEndOfStream Then
            ReDim returnValues(0)
            returnValues(0) = "None"
        Else
            contents = rFile.ReadAll
            rFile.Close
            For each c in Split(contents, VbCrLf)
                If Len(Trim(c)) > 0 Then
                    newContents = newContents & c & VbCrLf
                End If
            Next
            arrContents = Split(newContents, vbcrlf)

            If last > UBOUND(arrContents) Then
                ReDim returnValues(UBOUND(arrContents) - 1)
            Else
                ReDim returnValues(last - 1)
            End If
            'There's one blank line in arrContents... the last one, so remove it from the For loop.
            Dim count
            count = Ubound(arrContents) - 1
            ReDim cleanList(count)
            For i = 0 to count
                cleanList(i) = arrContents(i)
            Next
           
            For rev = UBOUND(returnValues) to LBOUND(returnValues) Step -1
                returnValues(rev) = cleanList(UBOUND(cleanList) - rev)
            Next
        End If
       
    Else
    'logfile doesn't exist, so create it, and add current computer to list.
        Set rFile = fso.CreateTextFile(logFileName)
        Set rFile = Nothing
        ReDim returnValues(0)
        returnValues(0) = "None"
    End If
    readLastEntry = returnValues
   
      Set objTextFile = Nothing
      Set nFile = Nothing
    Set fso = Nothing
    Set rFile = Nothing
End Function
'===============

'===============
Function getRowInfo(searchInfo)
    Dim retVals()
    Const ForReading = 1    
    logFileName = "log.txt"

    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(logFileName) = True Then
        Set rFile = fso.OpenTextFile(logFileName, ForReading)
        If rFile.AtEndOfStream Then
            ReDim retVals(0)
            retVals(0) = "None"
        Else
            contents = rFile.ReadAll
            rFile.Close
            arrContents = Split(contents, vbcrlf)
            If UBOUND(Filter(arrContents, searchInfo)) > -1 Then
                tmpVals = Split(Filter(arrContents, searchInfo)(0), "|")
                ReDim retVals(UBOUND(tmpVals) - 1)
                retVals(0) = tmpVals(1)
                retVals(1) = tmpVals(2)
                retVals(2) = tmpVals(3)
            Else
                ReDim retVals(0)
                retVals(0) = "None"
            End If
        End If
    End If
    getRowInfo = retVals
   
    Set fso = Nothing
    Set rFile = Nothing
End Function
'===============

'===============
Function logImagedComputers(thisPC)
Dim returnValues()
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

logFileName = "log.txt"

Dim arrDel()
Dim cleanList()
Dim i
Dim newContents

Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(logFileName) = True Then
    Set rFile = fso.OpenTextFile(logFileName, ForReading)
    If rFile.AtEndOfStream Then
        newContents = newContents & thisPC
    Else
        contents = rFile.ReadAll
        rFile.Close
        For each c in Split(contents, VbCrLf)
            If Len(Trim(c)) > 0 Then
                newContents = newContents & c & VbCrLf
            End If
        Next
        newContents = newContents & thisPC
    End If

Else
'logfile doesn't exist, so create it, and add current computer to list.
    Set rFile = fso.CreateTextFile(logFileName)
    Set rFile = Nothing
    newContents = thisPC
End If

Set objTextFile = fso.OpenTextFile(logFileName, ForWriting)
    objTextFile.WriteLine(newContents)
    objTextFile.Close
   
Set objTextFile = Nothing
Set nFile = Nothing
Set fso = Nothing
Set rFile = Nothing
End Function
'===============

'===============
Function vcAction(sender)
    Select Case sender.value
        Case "Remove"
            document.getElementById("adminInfo").style.display = ""
            document.getElementById("renameRow").style.display = "none"
            'msgbox(sender.value)
        Case "Add"
            document.getElementById("adminInfo").style.display = ""
            document.getElementById("renameRow").style.display = "none"
            'msgbox(sender.value)
        Case "Rename"
            document.getElementById("adminInfo").style.display = "none"
            document.getElementById("renameRow").style.display = ""
    End Select    
End Function
'===============

'===============
Function checkKey(sender)
    keyval=window.event.keyCode
    Select Case sender.id
        Case "tdAdd"
            If keyval = 13 or keyval = 27 Then
                Dim scope
                If sender.children("rbScope")(0).checked then
                    scope = sender.children("rbScope")(0).value
                Else
                    scope = sender.children("rbScope")(1).value
                End If    
                Msgbox(scope & "\" & sender.children("txtAddUserID").value)
                hideOptions(0)
            End If
        Case "tdRemove"
            If keyval = 13 or keyval = 27 Then
                        Msgbox("This function has not been implemented yet.")
                hideOptions(1)
                'Msgbox(sender.children("txtAddUserID").value)
            End If
        Case "tdExport"
            If keyval = 13 or keyval = 27 Then
                Dim t
                        Set t = document.Forms("BackupAccountsForm")
                If t.UList.selectedindex > -1 Then
                            Dim selUser
                            selUser = t.UList(t.UList.selectedindex).value
                            If Ubound(Split(Trim(selUser), ".")) > -1 Then
                        selUser = Split(Trim(selUser), ".")(0)
                    End If
                    If Len(currUser) > 0 And Len(Trim(selUser)) > 0 Then
                        If pathExists(sender.children("txtExportTo").value) Then
                            checkPath = fullPath(sender.children("txtExportTo").value)
                                        Dim r
                                        pc = currComputer
                                        userID = currUser
                                        userSID = vcUserSid.InnerHTML
                                        profilePath = checkPath & "\" & currComputer & "\" & currUser
                                        importRow = pc & "|" & userID & "|" & userSID & "|" & profilePath
                                        r = writeUserInfo(currUser, checkPath)
                              r = r & vbcrlf & logImagedComputers(importRow)
                              Msgbox(r)
                                        'r = r & vbcrlf & logImagedComputers(currComputer)
                                        'MSGBOX(r)
                            'Msgbox("Export " & curruser & " profile to " & sender.children("txtExportTo").value)
                        Else
                            Msgbox("Cannot Export " & curruser & " profile to " & sender.children("txtExportTo").value)
                        End If
                    End If
                        Else
                            Msgbox("No user to export")
                        End If
                hideOptions(2)
            End If    
        Case "tdImport"
            If keyval = 13 or keyval = 27 Then
                checkPath = fullPath(sender.children("txtImportFrom").value)
                checkLog = getRowInfo(checkPath)
                Stop
                If checkLog(0) = "None" Then
                    Msgbox("No account to import from path selected")
                Else
                   
                    AddResult = AddUser(checkLog(0), checkLog(1), currComputer)
                      'conResult = setContext(CurrentUserContext.InnerHTML)
                      MSGBOX(AddResult)
                      'MSGBOX(setContext)
                    'If Len(currUser) > 0 Then
                    '    Msgbox("Import " & currUser & " profile from " & sender.children("txtImportFrom").value)
                    'End If
                End If
                hideOptions(3)
            End If
        Case "strAdminID"
            If keyval = 13 or keyval = 27 Then
                document.getElementById("strAdminPW").focus
            End If
        Case "strAdminPW"
            If keyval = 13 or keyval = 27 Then
                result = ""
                For each rb in Document.Forms("BackupAccountsForm").rbAction
                        If rb.checked=true then
                              Select Case rb.value
                                    Case "Remove"
                                          result = updateComputer("Remove")
                                          MSGBOX(result)
                                          If Instr(result, "Fail") > 0 Then
                                              Call Reboot
                                          End If
                                    Case "Rename"
                                        result = updateComputer("Rename")
                                          MSGBOX(result)
                                          If Instr(result, "Fail") > 0 Then
                                              Call Reboot
                                          End If
                                    Case "Add"
                                        result = updateComputer("Add")
                                          MSGBOX(result)
                                          Call Reboot
                            End Select
                        End If
                  Next    
            End If        
        Case "strNewPCName"
            If keyval = 13 or keyval = 27 Then
                document.getElementById("adminInfo").style.display = ""
                document.getElementById("strAdminID").focus
            End If
    End Select
End Function
'===============

'===============
Function fullPath(path)
    Dim fsoCheck
    Set fsoCheck = CreateObject("Scripting.FileSystemObject")
    Set f = fsoCheck.GetFolder(path)
    If f.Drive.DriveType = 3 Then
        fullPath = Replace(f.Path, f.Drive.Path, f.Drive.ShareName)
    Else
        fullPath = f.Path
    End If
    Set f = Nothing
    Set fsoCheck = Nothing
End Function
'===============

'===============
Function setContext(context)

Const HKLM = &H80000002
Dim i
i = Split(context, ":")

user = i(0)
context = i(1)
server = i(2)
ntDefault = i(0)

strKey = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default"
strValue = "UserName"

strKey2 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab1"
strValue2 = "Context"

strKey3 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab1"
strValue3 = "Server"

strKey4 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab3"
strValue4 = "DefaultUserName"

strComputer = currComputer

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.SetStringValue HKLM,strKey,strValue,user
set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.SetStringValue HKLM,strKey2,strValue2,context
Set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.SetStringValue HKLM,strKey3,strValue3,server
Set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.SetStringValue HKLM,strKey4,strValue4,ntDefault
Set oReg = Nothing

setContext = "Set Context successfully."
End Function
'===============

'===============
Function getContext
Const HKLM = &H80000002
strKey1 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default"
strValue1 = "UserName"
Dim strNovID

strKey2 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab1"
strValue2 = "Context"
Dim strNovContext

strKey3 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab1"
strValue3 = "Server"
Dim strNovServer

strKey4 = "SOFTWARE\Novell\Location Profiles\Services\{1E6CEEA1-FB73-11CF-BD76-00001B27DA23}\Default\Tab3"
strValue4 = "DefaultUserName"
Dim strNTID

strComputer = currComputer

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.GetStringValue HKLM,strKey1,strValue1,strNovID
strVal1 = UCase(strVal1)
set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.GetStringValue HKLM,strKey2,strValue2,strNovContext
Set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.GetStringValue HKLM,strKey3,strValue3,strNovServer
If strNovServer = "" Then
      strNovServer = "NOSERV"
End If
Set oReg = Nothing

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
oReg.GetStringValue HKLM,strKey4,strValue4,strNTID
If strNTID = "" Then
      strNTID = "NONTID"
End If
Set oReg = Nothing
getContext = strNovID & ":" & strNovContext & ":" & strNovServer & ":" & strNTID
End Function
'===============

'===============
Function AddUser(userID, userIDSID, strComputer)
If instr(checkWinVer(currComputer), "Vista") > 0 Then
    AddUser = "Cannot Create Profile"
    Exit Function
Else
    'This is for when creating a Vista local profile is available.
    userPath = "\Documents and Settings"
End If
Const HKLM = &H80000002
strKey = "Software\Microsoft\Windows NT\CurrentVersion\ProfileList"

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strUserKeyPath = strKey & "\" & userIDSID
oReg.CreateKey HKLM, strUserKeyPath

strKeyPath = strKey & "\" & userIDSID

strUserCentPathKeyName = "CentralProfile"
strUserCentPathValue = ""
oReg.SetStringValue HKLM,strKeyPath,strUserCentPathKeyName,strUserCentPathValue

strUserPathKeyName = "ProfileImagePath"
strUserPathValue = "%SystemDrive%\Documents and Settings\" & userID
oReg.SetExpandedStringValue HKLM,strKeyPath,strUserPathKeyName,strUserPathValue

strUserFlagKeyName = "Flags"
strUserFlagValue = 1
oReg.SetDWORDValue HKLM,strKeyPath,strUserFlagKeyName,strUserFlagValue

Set oReg = Nothing

Set ProfileFolder=CreateObject("Scripting.FileSystemObject")
defaultUser = "C:\Documents and Settings\Default User"
newUser = "C:\Documents and Settings\" & userID
If ProfileFolder.FolderExists(defaultUser) Then
   ProfileFolder.CopyFolder defaultUser, newUser
End If
Set ProfileFolder=Nothing

AddUser = "Successfully created profile for: " & userID
End Function
'===============

'===============
Function pathExists(path)
    Dim p
    Set p = CreateObject("Scripting.FileSystemObject")
        pathExists = false
        If p.FolderExists(path) = true Then
            pathExists = true
            Exit Function
        End If
    Set p = Nothing        
End Function
'===============

'===============
Function writeUserInfo(user, saveTo)
Dim objFSO, objFolder, objShell, objTextFile, objFile
Dim strDirectory, strFile, strText, strCopyDir

strDirectory = saveTo

strCopyDir = strDirectory & "\" & currComputer
strFile = "\" & currUser & ".txt"
strText = " Data"

If instr(checkWinVer(currComputer), "Vista") > 0 Then
    FromPath = "\\" & currComputer & "\C$\Users\" & currUser
Else
    FromPath = "\\" & currComputer & "\C$\Documents and Settings\" & currUser
End If
ToPath = strCopyDir & "\" & currUser

Dim printers
Dim thisFrm
Dim drives
Dim folders
Dim biosInf
Dim iPopCon

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strDirectory folder exists
If objFSO.FolderExists(strCopyDir) = False Then
      Set objFolder = objFSO.CreateFolder(strCopyDir)
      Set objFolder = Nothing
      strCopyDir = strCopyDir & "\" & currUser
      If objFSO.FolderExists(strCopyDir) = False Then
            Set objFolder = objFSO.CreateFolder(strCopyDir)
      End If
Else
      strCopyDir = strCopyDir & "\" & currUser
      If objFSO.FolderExists(strCopyDir) = False Then
            Set objFolder = objFSO.CreateFolder(strCopyDir)
      End If
End If

If objFSO.FileExists(strCopyDir & strFile) = False Then
   Set objFile = objFSO.CreateTextFile(strCopyDir & strFile)
End If

Set objFile = Nothing
Set objFolder = Nothing
Const ForAppending = 8

Set thisFrm = Document.Forms("BackupAccountsForm")

biosInf = thisFrm.VCBIOS.value

printers = thisFrm.PrinterInfo.value

drives = thisFrm.driveInfo.value

folders = copyFolders(FromPath, strCopyDir)

iPopCon = GetiPopConfig(fromPath, toPath)

Set objTextFile = objFSO.OpenTextFile(strCopyDir & strFile, ForAppending, True)

strText = "USERID:" & currUser & vbcrlf _
& "USERSID:" & vcUserSid.InnerHTML & vbcrlf _
& "USERPRINTERS:" & printers & vbcrlf _
& "USERDRIVES:" & drives & vbcrlf _
& "USERPROFILEFOLDERS:" & folders & vbcrlf _
& "USERIPOPCONFIG:" & iPopCon & vbcrlf _
& currComputer & "CONFIG:" & biosInf & vbcrlf _
& currComputer & "IPADDRESS:" & VCIP.InnerHTML & vbcrlf _
& "DEFAULTNOVELLINFO:" & vcUserNovellData.InnerHTML
objTextFile.WriteLine(strText)
objTextFile.Close
Set objTextFile = Nothing
Set thisFrm = Nothing
writeUserInfo = "Successfully stored profile data for " & currUser & " from PC:" & currComputer & "."
End Function
'===============

'===============
Function checkWinVer(strComputer)
Const Impersonate = "winmgmts:{impersonationLevel=impersonate}!\\"
aryServers = strComputer

Set oWMI = GetObject(Impersonate & aryServers & "\root\cimv2")
Set QueryWMI = oWMI.ExecQuery("SELECT * FROM Win32_OperatingSystem")
For Each oItem In QueryWMI
    Select Case oItem.osType
        Case 0
            osType = "(0x0) Unknown"
        Case 1
            osType = "(0x1) Other"
        Case 2
            osType = "(0x2) MACROS"
        Case 3
            osType = "(0x3) ATTUNIX"
        Case 4
            osType = "(0x4) DGUX"
        Case 5
            osType = "(0x5) DECNT"
        Case 6
            osType = "(0x6) Digital UNIX"
        Case 7
            osType = "(0x7) OpenVMS"
        Case 8
            osType = "(0x8) HPUX"
        Case 9
            osType = "(0x9) AIX"
        Case 10
            osType = "(0xA) MVS"
        Case 11
            osType = "(0xB) OS400"
        Case 12
            osType = "(0xC) OS/2"
        Case 13
            osType = "(0xD) JavaVM"
        Case 14
            osType = "(0xE) MSDOS"
        Case 15
            osType = "(0xF) WIN3x"
        Case 16
            osType = "(0x10) WIN95"
        Case 17
            osType = "(0x11) WIN98"
        Case 18
            osType = "(0x12) WINNT"
        Case 19
            osType = "(0x13) WINCE"
        Case 20
            osType = "(0x14) NCR3000"
        Case 21
            osType = "(0x15) NetWare"
        Case 22
            osType = "(0x16) OSF"
        Case 23
            osType = "(0x17) DC/OS"
        Case 24
            osType = "(0x18) Reliant UNIX"
        Case 25
            osType = "(0x19) SCO UnixWare"
        Case 26
            osType = "(0x1A) SCO OpenServer"
        Case 27
            osType = "(0x1B) Sequent"
        Case 28
            osType = "(0x1C) IRIX"
        Case 29
            osType = "(0x1D) Solaris"
        Case 30
            osType = "(0x1E) SunOS"
        Case 31
            osType = "(0x1F) U6000"
        Case 32
            osType = "(0x20) ASERIES"
        Case 33
            osType = "(0x21) TandemNSK"
        Case 34
            osType = "(0x22) TandemNT"
        Case 35
            osType = "(0x23) BS2000"
        Case 36
            osType = "(0x24) LINUX"
        Case 37
            osType = "(0x25) Lynx"
        Case 38
            osType = "(0x26) XENIX"
        Case 39
            osType = "(0x27) VM/ESA"
        Case 40
            osType = "(0x28) Interactive UNIX"
        Case 41
            osType = "(0x29) BSDUNIX"
        Case 42
            osType = "(0x2A) FreeBSD"
        Case 43
            osType = "(0x2B) NetBSD"
        Case 44
            osType = "(0x2C) GNU Hurd"
        Case 45
            osType = "(0x2D) OS9"
        Case 46
            osType = "(0x2E) MACH Kernel"
        Case 47
            osType = "(0x2F) Inferno"
        Case 48
            osType = "(0x30) QNX"
        Case 49
            osType = "(0x31) EPOC"
        Case 50
            osType = "(0x32) IxWorks"
        Case 51
            osType = "(0x33) VxWorks"
        Case 52
            osType = "(0x34) MiNT"
        Case 53
            osType = "(0x35) BeOS"
        Case 54
            osType = "(0x36) HP MPE"
        Case 55
            osType = "(0x37) NextStep"
        Case 56
            osType = "(0x38) PalmPilot"
        Case 57
            osType = "(0x39) Rhapsody"
    End Select
    Select Case oItem.ProductType
        Case 1
            pType = "Workstation"
        Case 2
            pType = "Domain Controller"
        Case 3
            pType = "Server"
    End Select
    If oItem.osType > 14 And oItem.osType < 20 Then
        checkWinVer = oItem.Caption & " " & oItem.CSDVersion & "" & osType & " " & pType
    Else
        checkWinVer = osType
    End If
Next
Set oWMI = Nothing
Set QueryWMI = Nothing
End Function
'===============

'===============
Function copyFolders(fromPath, toPath)
Dim FSO
Dim progress
Dim Desktop, Favorites, MyDocs, MyRecent

If instr(checkWinVer(currComputer), "Vista") > 0 Then
    Desktop = FromPath & "\Desktop"
    Favorites = FromPath & "\Favorites"
    MyDocs = FromPath & "\Documents"
    'MyRecent = FromPath & "\My Recent Documents"
    'Would be C:\Users\[UserID]\AppData\Roaming\Microsoft\Windows
Else
    Desktop = FromPath & "\Desktop"
    Favorites = FromPath & "\Favorites"
    MyDocs = FromPath & "\My Documents"
    MyRecent = FromPath & "\My Recent Documents"
End If

If Right(FromPath, 1) = "\" Then
   FromPath = Left(FromPath, Len(FromPath) - 1)
End If

If Right(ToPath, 1) = "\" Then
   ToPath = Left(ToPath, Len(ToPath) - 1)
End If

Set FSO = CreateObject("Scripting.FileSystemObject")

If FSO.FolderExists(FromPath) = False Then
    copyFolders = FromPath & " doesn't exist."
Else
On Error Resume Next
    'Desktop
      If FSO.FolderExists(ToPath & "\Desktop") = False Then
            FSO.CreateFolder(ToPath & "\Desktop")      
      End If
       FSO.CopyFolder Desktop & "\*", ToPath & "\Desktop", True
       FSO.CopyFile   Desktop & "\*.*", ToPath & "\Desktop", True
       progress = "Desktop copied successfully." & vbcrlf

    'Favorites
      If FSO.FolderExists(ToPath & "\Favorites") = False Then
            FSO.CreateFolder(ToPath & "\Favorites")      
      End If    
       FSO.CopyFolder Favorites & "\*", ToPath & "\Favorites", True
       FSO.CopyFile   Favorites & "\*.*", ToPath & "\Favorites", True
       progress = progress & "Favorites copied successfully." & vbcrlf

    'My Documents
      If FSO.FolderExists(ToPath & "\My Documents") = False Then
            FSO.CreateFolder(ToPath & "\My Documents")
        'progress = progress & "Created My Documents folder on new PC." & vbcrlf      
      End If
      If FSO.FolderExists(MyDocs) = True Then
            progress = progress & MyDocs & " path exists." & vbcrlf
      End If
           FSO.CopyFolder MyDocs & "\*", ToPath & "\My Documents", True
           FSO.CopyFile   MyDocs & "\*.*", ToPath & "\My Documents", True
           progress = progress & "My Documents copied successfully." & vbcrlf
    'My Recent Documents
      If FSO.FolderExists(ToPath & "\My Recent Documents") = False Then
            FSO.CreateFolder(ToPath & "\My Recent Documents")
            progress = progress & "Created My Recent Documents folder on new PC." & vbcrlf      
      End If
      If FSO.FolderExists(MyRecent) = True Then
            progress = progress & MyRecent & " path exists." & vbcrlf
      End If
           FSO.CopyFolder MyRecent & "\*", ToPath & "\My Recent Documents", True
           FSO.CopyFile   MyRecent & "\*.*", ToPath & "\My Recent Documents", True
           progress = progress & MyRecent & " copied successfully." & vbcrlf

           copyFolders = progress
End If
Set FSO = Nothing
'Exit Sub
End Function
'===============

'===============
Function explorePath(sender)
    If pathExists(sender.InnerHTML) = True Then
        Set ObjShell = CreateObject("WScript.Shell")
        strPath = sender.InnerHTML
        objShell.Run "explorer.exe /e, " & strPath
    Else
        Msgbox("Path does not exist: " & strPath)
    End If
End Function
'===============

'===============
Sub VCNameChange
      Dim vcNameField
      Dim vcInputNameField
      Set vcNameField = Document.GetElementByID("VCName")
      Set vcInputNameField = Document.GetElementByID("strTargetPC")

      vcNameField.style.visibility = "hidden"
      Set vcNameField = Nothing
      With vcInputNameField
        .value = VCName.InnerHTML
        .style.visibility = "visible"
    End With
      
      Set vcInputNameField = Nothing
End Sub
'===============

'===============
Sub selectText

End Sub
'===============

'===============
Sub italics
      Dim vcNameField
      Set vcNameField = Document.GetElementByID("VCName")
      With vcNameField
            .style.fontStyle = "italic"
            .style.fontWeight = "bold"
            .style.backgroundColor = "#778899"
      End With
      Set vcNameField = Nothing
End Sub
'===============

'===============
Sub normal
      Dim vcNameField
      Set vcNameField = Document.GetElementByID("VCName")
      With vcNameField
            .style.fontStyle = "normal"
            .style.fontWeight = "normal"
            .style.backgroundColor = ""
      End With
      Set vcNameField = Nothing
End Sub
'===============

'===============
Sub link
      Dim vcLinkField
      Set vcLinkField = Document.GetElementByID("VCLink")
      With vcLinkField
            .style.textDecoration = "underline"
        .style.cursor = "hand"
      End With
      Set vcLinkField = Nothing
End Sub
'===============

'===============
Sub linkNormal
      Dim vcLinkField
      Set vcLinkField = Document.GetElementByID("VCLink")
      With vcLinkField
            .style.textDecoration = "none"
            .style.cursor = "default"
      End With
      Set vcLinkField = Nothing
End Sub
'===============

'===============
Sub testNewVal
    Dim viewedComputerField
      Set viewedComputerField = Document.GetElementByID("VCName")
    Dim inputTargetPC
    Set inputTargetPC = document.getElementByID("strTargetPC")
      'Msgbox(pingPC(inputTargetPC.value))
      If Not inputTargetPC.value = viewedComputerField.InnerHTML And Not Trim(inputTargetPC.value) = "" And testPing(inputTargetPC.value) = True Then
            r = Split(pingPC(inputTargetPC.value), ";")
            If Split(r(1), ":")(1) = 0 Then
                  Msgbox((Split(r(0), ":")(1)) & " is offline.")
                  inputTargetPC.style.visibility = "hidden"
                  viewedComputerField.style.visibility = "visible"
            Else
                  currComputer = Split(r(0), ":")(1)
                  VCLink.InnerHTML = currComputer
                  SetStatus(r(1))
                  SetIP(r(2))
                  SetDomain(r(3))
                inputTargetPC.style.visibility = "hidden"
                  viewedComputerField.style.visibility = "visible"
                  viewedComputerField.InnerHTML = inputTargetPC.value
            End If
      Else
          inputTargetPC.style.visibility = "hidden"
          viewedComputerField.style.visibility = "visible"
      End If
      Set inputTargetPC = Nothing
      Set viewedCOmputerField = Nothing
End Sub
'===============

'===============
Sub setDomain(strInfo)
      VCDomainLbl.InnerHTML = Split(strInfo, ":")(0)
      VCDomainName.InnerHTML = Split(strInfo, ":")(1)
End Sub
'===============

'===============
Sub setIP(strInfo)
      VCIP.InnerHTML = Split(strInfo, ":")(1)
End Sub
'===============

'===============
Sub setStatus(strInfo)
      If Split(strInfo, ":")(1) = 0 Then
            VCStatus.InnerHTML = "Offline"
      Else
            VCStatus.InnerHTML = "Online"
      End If
End Sub
'===============

'===============
Sub btnShow_OnClick
      Dim oShell
      runText = """BackupAccounts.HTA""" & """Computer:" & currComputer & "" & """User:" & currUser & ""
      Set oShell = CreateObject("WScript.Shell")
      oShell.Run runText
      Set oShell = Nothing
      Self.Close
End Sub
'===============

'===============
Sub tabClicked(val)
    Dim tabBIOS, tabAccounts, tabOther
    Dim tabBIOSHeader, tabAccountsHeader, tabOtherHeader
    Set tabBIOS = document.getElementById("BIOSTab")
    Set tabBIOSHeader = document.getElementById("BIOSHeader")
    Set tabAccounts = document.getElementById("AccountTab")
    Set tabAccountsHeader = document.getElementById("AccountsHeader")
    Set tabOther = document.getElementById("OtherTab")
    Set tabOtherHeader = document.getElementById("OtherHeader")
   
    Select Case val
        Case 0
            'Msgbox("BIOS Tab clicked")
            tabBIOS.className = "tabVisible"
            tabBIOSHeader.classname = "tabHeaderSelected"
            tabBIOSHeader.parentElement.classname = "tabHeaderSelectedCell"
            tabAccounts.className = "tabNotVisible"
            tabAccountsHeader.className = "tabHeaderNotSelected"
            tabAccountsHeader.parentElement.className = "tabHeaderNotSelectedCell"
            tabOther.className = "tabNotVisible"
            tabOtherHeader.className = "tabHeaderNotSelected"
            tabOtherHeader.parentElement.className = "tabHeaderNotSelectedCell"
        Case 1
            tabBIOS.className = "tabNotVisible"
            tabBIOSHeader.classname = "tabHeaderNotSelected"
            tabBIOSHeader.parentElement.classname = "tabHeaderNotSelectedCell"
            tabAccounts.className = "tabVisible"
            tabAccountsHeader.className = "tabHeaderSelected"
            tabAccountsHeader.parentElement.classname = "tabHeaderSelectedCell"
            tabOther.className = "tabNotVisible"
            tabOtherHeader.className = "tabHeaderNotSelected"
            tabOtherHeader.parentElement.className = "tabHeaderNotSelectedCell"
        Case 2
            tabBIOS.className = "tabNotVisible"
            tabBIOSHeader.classname = "tabHeaderNotSelected"
            tabBIOSHeader.parentElement.classname = "tabHeaderNotSelectedCell"
            tabAccounts.className = "tabNotVisible"
            tabAccountsHeader.className = "tabHeaderNotSelected"
            tabAccountsHeader.parentElement.className = "tabHeaderNotSelectedCell"
            tabOther.className = "tabVisible"
            tabOtherHeader.className = "tabHeaderSelected"
            tabOtherHeader.parentElement.className = "tabHeaderSelectedCell"
    End Select
    Set tabBIOS = Nothing
    Set tabBIOSHeader = Nothing
    Set tabAccounts = Nothing
    Set tabAccountsHeader = Nothing
    Set tabOther = Nothing
    Set tabOtherHeader = Nothing
End Sub
'===============

'===============
Function getLocalComputerName(strComputer)
If strComputer <> "" Then
      If strComputer = "." Then
            local = 1
      Else
            local = 0
      End If

On Error Resume Next
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    If Err.Number = 0 Then
        Set colItems = objWMIService.ExecQuery("Select * From Win32_ComputerSystem")
            For Each objItem in colItems
                  getLocalComputerName = objItem.Name
            Next
            Set colItems = Nothing
    Else
        getLocalComputerName = "# " & Err.Description
    End If
    Set objWMIService = Nothing
    Err.Clear
End If
End Function
'===============

'===============
Function domainOrWorkgroup(strComputer)
      If strComputer = "." Then
            Set objWMISvc = GetObject("winmgmts:\\.\root\cimv2")
      Else
            Set objWMISvc = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      End If
      
      Set colItems = objWMISvc.ExecQuery("Select * from Win32_ComputerSystem", ,48)
      For Each objItem in colItems
            strComputerDomain = objItem.Domain
            If objItem.PartOfDomain Then
                  domainOrWorkgroup = "1:" & strComputerDomain
                  'Msgbox "Computer Domain:" & strComputerDomain
            Else
                  domainOrWorkgroup = "0:" & strComputerDomain
                  'Msgbox "Workgroup:" & strComputerDomain
            End If
      Next
      Set objWMISvc = Nothing
      Set colItems = Nothing
End Function
'===============

'===============
Function launch
      Dim runText
      Set oShell = CreateObject("WScript.Shell")
      runText = "mstsc.exe /v " & Trim(VCLink.InnerHTML)
      oShell.Run runText
      Set oShell = Nothing
End Function
'===============

'===============
Function pingPC(strComputer)
      'Returns String Computer:XXXXX;Status:int;IP:XXX.XXX.XXX.XXX;DomainRole:XXXXX
      '0 Computer:[Value];
      '1 Status:[Value - 0 offline, 1 online];
      '2 IP:[value];
      '3 DomainRole:[value - Domain or Workgroup]
      Dim objPing
      Dim r
      r = ""
    Set objPing = GetObject("winmgmts:\\" & strComputer & "\root\cimv2").ExecQuery("select * from Win32_PingStatus where address = '" & strComputer & "'")
    For Each objStatus in objPing
        If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
            r = "Computer:" & strComputer & ";Status:0;IP:" & objStatus.ProtocolAddress & ";0:0"
        Else
            r = "Computer:" & strComputer & ";Status:1;IP:" & objStatus.ProtocolAddress
                  Set colComputer = GetObject("winmgmts:\\" & strComputer & "\root\cimv2").ExecQuery("Select DomainRole, Domain from Win32_ComputerSystem")
                  For Each oComputer in colComputer
                        iDR = oComputer.DomainRole
                        sName = oComputer.Domain
                  Next
                  If iDR = 0 Or iDR = 2 Then
                        r = r & ";Workgroup:" & sName
                  Else
                        r = r & ";Domain:" & sName
                  End If
        End If
    Next
      Set objPing = Nothing
      Set colComputer = Nothing
      pingPC = r
End Function
'===============

'===============
Function testPing(strComputer)
If (IsConnectible(strComputer, 1, 750) = True) Then
    testPing = True
Else
    testPing = false
End If
End Function
'===============

'===============
Function IsConnectible(ByVal strHost, ByVal intPings, ByVal intTO)
Dim lngResult
Set objShell = CreateObject("Wscript.Shell")
If (intPings = "") Then
    intPings = 2
End If
If (intTO = "") Then
    intTO = 750
End If
'Stop
lngResult = objShell.Run("%comspec% /c ping -4 -n " & intPings & " -w " & intTO & " " & strHost & " | find ""TTL="" > nul 2>&1", 0, True)
    Select Case lngResult
        Case 0
            IsConnectible = True
        Case Else
            IsConnectible = False
    End Select
End Function
'===============

'===============
Function getBIOS(strComputer)
      Dim result
      result = ""
      Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      Set colSMBIOS = objWMIService.ExecQuery ("Select * from Win32_SystemEnclosure")
      For Each objSMBIOS in colSMBIOS
            result = result & "Part Number: " & objSMBIOS.PartNumber & vbcrlf
            result = result & "Serial Number: " & objSMBIOS.SerialNumber & vbcrlf
            result = result & "Asset Tag: " & objSMBIOS.SMBIOSAssetTag
      Next
      Set objWMIService = Nothing
      getBIOS = result
End Function
'===============

'===============
Function getRemoteDrives(strComputer)
Dim response
If strComputer <> "" Then
'Set objDrives = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer).InstancesOf("Win32_LogicalDisk")
'Set objDrives = GetObject("winmgmts:\\" & strComputer).InstancesOf("Win32_MappedLogicalDisk")
Set objDrives = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer).InstancesOf("Win32_MappedLogicalDisk")
response = "Connected." & vbcrlf
For Each INST in objDrives
      response = response & (INST.deviceid) & vbTAB & (INST.ProviderName) & vbcrlf
Next
End If
Set objDrives = Nothing
getRemoteDrives = response
End Function
'===============

'===============
Sub DivChange (yesnobox, layername)
      Dim strObjName
      strObjName = "document.MainForm." & yesnobox & ".value"
      If eval(strObjName) = "No" Then
      document.getElementById(layername).style.display = "block"
      Elseif eval(strObjName) = "Yes" then
      document.getElementById(layername).style.display = "none"
      End If
End Sub
'===============

'===============
Function visible(t)
    Dim row
    Dim labelAction
    Select Case t
        Case 0
            Set row = document.getElementById("VCBIOSRow")
            rowVal = document.getElementById("VCBIOSRow").style.display
            Set labelAction = document.getElementById("VCBIOSRowAction")
            if rowVal = "none" then
                row.style.display = ""
                labelAction.InnerHTML = "(Hide)"
            else
               row.style.display = "none"
               labelAction.InnerHTML = "(Show)"
            end if
        Case 1
            Set row = document.getElementById("userRow")
            rowVal = document.getElementById("userRow").style.visibility
            Set labelAction = document.getElementById("userRowLabelAction")
            if rowVal = "visible" then
                row.style.visibility = "hidden"
                labelAction.InnerHTML = "(Show)"
            else
               row.style.visibility = "visible"
               labelAction.InnerHTML = "(Hide)"
            end if
        Case 2
       
        Case Else
       
    End Select
      Set row = Nothing
      Set labelAction = Nothing
End Function
'===============

'===============
Function GetiPopConfig(fromPath, toPath)
      Set configFileObj=CreateObject("Scripting.FileSystemObject")
      If currComputer = "." Then
            configFile = "C:\GCTI\iPop\Config\config.xml"
      Else
            configFile = "\\" & currComputer & "\C$\GCTI\iPop\Config\config.xml"
      End If

      newUser = toPath & "\config.XML"

      If configFileObj.FileExists(configFile) Then
            configFileObj.copyFile configFile, newUser
            Set configFileObj = Nothing
            GetiPopConfig = "Successfully stored iPop Config."
      Else
            GetiPopConfig = "No iPop config"
      End If
End Function
'===============

'===============
Function getUsersList
Dim c
c = getComputerLocalAccounts(".")
Dim Rows
Rows = UBound(c, 2)
Dim size
size = Rows + 2
    getUsersList = "<select name=""UList"" SIZE=""" & size & """ style=""Width:150px; DISPLAY: block; OVERFLOW: auto; BORDER-TOP-STYLE: none;  BORDER-BOTTOM-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; background-color=#778899"" OnChange=""display()"">"
        For i = 0 To Rows
            getUsersList = getUsersList & "<option value=""" & c(0, i) & """>"
                  getUsersList = getUsersList & c(0, i)
        Next
    getUsersList = getUsersList & "</select>"
End Function
'===============

'===============
Sub display()
      Dim t
      Set t = document.Forms("BackupAccountsForm")
      Dim selUser
      If UBOUND(Split(t.UList(t.UList.selectedIndex).value)) > -1 Then
            selUser = Split(t.UList(t.UList.selectedindex).value, ".")(0)
          If Not selUser = currUser Then
                vcUser = selUser
                vcLoggedOnUser.InnerHTML = vcUser
            If VCDomainLbl.InnerHTML = "Domain" Then
                    strUserSID = getSIDasString(vcUser)
                    vcUserSid.InnerHTML = strUserSID
                End If
                vcUserID.InnerHTML = vcUser
                vcUserNovellData.InnerHTML = getContext
                
                Dim printers
                printers = printerList(currComputer)
                t.printerInfo.value = printers

                Dim drives
                drives = driveList(currComputer)
                t.driveInfo.value = drives

                document.GetElementByID("VCBIOS").value = getBIOS(currComputer)
                currUser = selUser
          End If
    End If
End Sub
'===============

'===============
Function driveList(strComputer)
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set drives = objWMIService.ExecQuery("Select * from Win32_MappedLogicalDisk")
Dim driveStr
For Each drive in drives
    Dim d
    d = drive.DeviceID & drive.ProviderName
    driveStr = driveStr & d & vbcrlf
Next
Set drives = Nothing
driveList = driveStr
End Function
'===============

'===============
Function getComputerLocalAccounts(strComputer)
Dim DocsSettings
Dim IDList()
If strComputer = "." Then
    DocsSettings = "C:\Documents and Settings\"
Else
    DocsSettings = "\\" & strComputer & "\C$\Documents and Settings\"
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(DocsSettings)
On Error Resume Next
Dim i, j
i = 0
j = 0
For Each f In objFolder.SubFolders
      If Not isException(UCase(f.Name)) Then
            If (DateDiff("d", f.DateLastModified, Now) < 30) Then
                If i = 0 Then
                    ReDim IDList(1, 0)
                Else
                    ReDim Preserve IDList(UBound(IDList, 1), UBound(IDList, 2) + 1)
                End If
                IDList(0, i) = UCase(f.Name)
                IDList(1, i) = UCase(f.DateLastModified)
                i = i + 1
            End If
      End If
Next
getComputerLocalAccounts = IDList
End Function
'===============

'===============
Function isException(ByVal foldername)
      select case foldername
            Case "ALL USERS"
            isException = True
            Case "DEFAULT USER"
            'Case "DEFAULT"
            isException = True
            Case "LOCALSERVICE"
            isException = True
            Case "NETWORKSERVICE"
            isException = True
            Case "ADMINISTRATOR"
            isException = True
            'Case "PUBLIC"
            'isException = True
            Case Else
            isException = False
      End Select
End Function
'===============

'===============
Function printerList(strComputer)
Const DEFAULT = 4
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set printers = objWMIService.ExecQuery("Select * from Win32_Printer")
Dim printerStr
For Each printer in printers
    Dim p
    if printer.Attributes And 4 then
          p = "(DEFAULT)PRINTER NAME:" & printer.Name & " | PORT:" & printer.PortName
    else
          p = "PRINTER NAME:" & printer.Name & " | PORT:" & printer.PortName
    end if
    printerStr = printerStr & p & vbcrlf
Next
Set objWMIService = Nothing
Set printers = Nothing
printerList = printerStr
End Function
'===============

'===============
Function getSIDasString(userID)
strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", userID, "adsPath")
If Left(strUserADsPath, 7) = "LDAP://" Then
      Set objUser = GetObject(strUserADsPath)
      arrSid = objUser.objectSid
      strSidHex = OctetToHexStr(arrSid)
      strSidDec = HexStrToDecStr(strSidHex)
      getSIDasString = strSidDec
Else
      getSIDasString = "Could not find adsPath for " & userID
End If
End Function
'===============

'===============
'Working VBScript Active Directory Binary SID conversion to String SID
' Source: http://forums.techarena.in/showthread.php?t=588078
'Function to convert OctetString (byte array) to Hex string.
Function OctetToHexStr(arrbytOctet)
Dim k
OctetToHexStr = ""
For k = 1 To Lenb(arrbytOctet)
OctetToHexStr = OctetToHexStr & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
Next
End Function
'===============

'===============
Function HexStrToDecStr(strSid)
' Function to convert Hex string Sid to Decimal string (SDDL) Sid.
 
' SID anatomy:
' Byte Position
' 0 : SID Structure Revision Level (SRL)
' 1 : Number of Subauthority/Relative Identifier
' 2-7 : Identifier Authority Value (IAV) [48 bits]
' 8-x : Variable number of Subauthority or Relative Identifier (RID) [32 bits]
'
' Example:
'
' <Domain/Machine>\Administrator
' Pos : 0 | 1 | 2 3 4 5 6 7 | 8 9 10 11 | 12 13 14 15 | 16 17 18 19 | 20 21 22 23 | 24 25 26 27
' Value: 01 | 05 | 00 00 00 00 00 05 | 15 00 00 00 | 06 4E 7D 7F | 11 57 56 7A | 04 11 C5 20 | F4 01 00 00
' str : S- 1 | | -5 | -21 | -2138918406 | -2052478737 | -549785860 | -500
 
Const BYTES_IN_32BITS = 4
Const SRL_BYTE = 0
Const IAV_START_BYTE = 2
Const IAV_END_BYTE = 7
Const RID_START_BYTE = 8
Const MSB = 3 'Most significant byte
Const LSB = 0 'Least significant byte
 
Dim arrbytSid, lngTemp, base, offset, i
 
ReDim arrbytSid(Len(strSid)/2 - 1)
 
' Convert hex string into integer Array
For i = 0 To UBound(arrbytSid)
      arrbytSid(i) = CInt("&H" & Mid(strSid, 2 * i + 1, 2))
Next
 
' Add SRL number
HexStrToDecStr = "S-" & arrbytSid(SRL_BYTE)
 
' Add Identifier Authority Value
lngTemp = 0
For i = IAV_START_BYTE To IAV_END_BYTE
      lngTemp = lngTemp * 256 + arrbytSid(i)
Next
HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
 
' Add a variable number of 32-bit subauthority or
' relative identifier (RID) values.
' Bytes are in reverse significant order.
' i.e. HEX 01 02 03 04 => HEX 04 03 02 01
' = (((0 * 256 + 04) * 256 + 03) * 256 + 02) * 256 + 01
' = DEC 67305985
For base = RID_START_BYTE To UBound(arrbytSid) Step BYTES_IN_32BITS
      lngTemp = 0
      For offset = MSB to LSB Step -1
            lngTemp = lngTemp * 256 + arrbytSid(base + offset)
      Next
      HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
Next
End Function ' HexStrToDecStr
'===============

'===============
Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
     
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '                        It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '                        For example, if you are searching based on the user account name, strSearchField
      '                        would be "samAccountName", and strObjectToGet would be that speicific account name,
      '                        such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '      strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '                        the home folder path, as defined by the AD, for a specific user, this would be
      '                        "homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '                        user and get your own parameters from them, then use "ADsPath" as a return string,
      '                        then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
     
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal
End Function
'===============

'===============
Function getUser(strComputer)
If strComputer <> "" Then
On Error Resume Next
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    If Err.Number = 0 Then
        Set system = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
        Dim userStr
        For Each user In system
            If InStr(user.UserName, "\") > 0 Then
                Dim u
                u = Split(user.UserName, "\")
                Dim userID
                userID = u(1)
            End If
        Next
            Set system = Nothing
        getUser = UCASE(TRIM(userID))
    Else
        getUser = "# " & Err.Description
    End If
    Set objWMIService = Nothing
    Err.Clear
End If
End Function
'===============

'===============
Function renameComputer(newName, strAdminName, strAdminPw)
Dim result
Set objWMIService = GetObject("Winmgmts:root\cimv2")

' Call always gets only one Win32_ComputerSystem object.
For Each objComputer in _
    objWMIService.InstancesOf("Win32_ComputerSystem")
        Return = objComputer.rename(newName,strAdminPW,strAdminName)
        If Return <> 0 Then
            renameComputer = False
        Else
            renameComputer = True
        End If
Next
End Function
'===============

'===============
Function updateComputer(action)
On Error Resume Next
Const JOIN_DOMAIN = 1
Const ACCT_CREATE = 2
Const ACCT_DOMAIN_JOIN_IF_JOINED = 32
Dim adminID
Dim adminPW
Dim result
domain = "" ' Set your domain
strDomain = "Domain.com" 'Set your DNS suffix
strOU = "OU=Default,DC=Domain,DC=com" 'Set the OU you want to add object to.

newName = Document.getElementById("strNewPCName").value

If Split(document.getElementById("strAdminID").value, "\")(0) = "" Then
    adminID = document.getElementById("strAdminID").value
    adminID = domain & "\" & adminID
Else
    adminID = document.getElementById("strAdminID").value
End If
adminPW = document.getElementById("strAdminPW").value

varExitErrorLevel = 0
Dim strCommand
Select Case action
      Case "Add" strCommand = "Join"
      Case "Rename" strCommand = "Rename"
      Case "Remove" strCommand = "Remove"
End Select

'Set objNetwork = CreateObject("WScript.Network")
'strHostName = objNetwork.ComputerName
'Set objNetwork = Nothing
Set objWMIComputer = GetObject("winmgmts:{impersonationLevel=Impersonate}!\\" & currComputer & "\root\cimv2:Win32_ComputerSystem.Name='" & strHostName & "'")
Select Case strCommand
      Case "Rename"
            If renameComputer(newName, adminID, adminPW) = False Then
                result = "Failed to rename computer."
            Else
                result = "Successfully renamed computer." & VbCrLf & "Please Reboot."
            End If
      Case "Join"
        varWMIJoinReturnValue = objWMIComputer.JoinDomainOrWorkGroup(strDomain, adminPW, adminID, strOU, JOIN_DOMAIN + ACCT_CREATE)
        If varWMIJoinReturnValue = 2224 Then
                  varWMIJoinReturnValue = objWMIComputer.JoinDomainOrWorkGroup(strDomain, adminPW, adminID, strOU, JOIN_DOMAIN)
            End If
            result = result & vbcrlf & "Successfully added to domain." & vbcrlf & varWMIJoinReturnValue
      Case "Remove"
          varWMIJoinReturnValue = objWMIComputer.UnJoinDomainOrWorkGroup(adminPW, adminID, 0)
          varExitErrorLevel = 0
        Set ADSISysInfo = CreateObject("ADSystemInfo")
        Set objADSIComputer = GetObject("LDAP://" & ADSISysInfo.ComputerName & "")
            objADSIComputer.DeleteObject(0)
        Set objADSIComputer = Nothing
        Set ADSISysInfo = Nothing
        result = result & vbcrlf & "Deleted domain computer account."
End Select
Set objWMIComputer = Nothing
updateComputer = result
End Function
'===============

'===============
Function fncErrorMessage(varErrorNumber, strErrorDescription, flgSetExitErrorLevel)
    If strErrorDescription = "" Then
        'List of system error codes and network management error codes
        Select Case varErrorNumber
            Case 5 strErrorDescription = "Access is denied"
            Case 87 strErrorDescription = "The parameter is incorrect"
            Case 110 strErrorDescription = "The system cannot open the specified object"
            Case 1323 strErrorDescription = "Unable to update the password"
            Case 1326 strErrorDescription = "Logon failure: unknown username or bad password"
            Case 1355 strErrorDescription = "The specified domain either does not exist or could not be contacted"
            Case 2224 strErrorDescription = "The account already exists"
            Case 2691 strErrorDescription = "The machine is already joined to the domain"
            Case 2692 strErrorDescription = "The machine is not currently joined to a domain"
        End Select
    End If
    fncErrorMessage = "Error: " & varErrorNumber & ". " & strErrorDescription & "."
    If flgSetExitErrorLevel Then varExitErrorLevel = 1
End Function
'===============

'===============
Dim oWMI, oOS, obj
Sub Reboot
      If Msgbox("Your Computer Needs to Reboot Before Changes Can be Made. " & vbCrLf & "Would you Like To Reboot Now?" , vbYesNo, Title) = vbYes then

      Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\.\root\cimv2")
      On Error GoTo 0
      For Each obj in oWMI.ExecQuery("Select * from Win32_OperatingSystem")
            Set oOS = obj
            Exit For
      Next
      Call ShutDownNow()
      End If
End Sub

Sub ShutDownNow
      Const EWX_LOGOFF = 0
      Const EWX_SHUTDOWN = 1
      Const EWX_REBOOT = 2
      Const EWX_FORCE = 4
      Const EWX_POWEROFF = 8
      oOS.Win32shutdown EWX_REBOOT '+ EWX_FORCE
End Sub
'===============

'===============
</SCRIPT>
</head>
<body bgcolor="#580000" style="padding-right: 0px; padding-left: 0px; padding-bottom: 0px;
    margin: 0px; padding-top: 0px; font-family: Arial, Helvetica, sans-serif; font-size: 12px;
    color: #FFFFFF;">
    <form id="BackupAccountsForm">
        <table style="border-collapse: collapse; width: 100%; height: 10% direction: ltr;
            padding-right: 1px; padding-left: 1px; border-left-color: black; border-top-style: double;
            border-top-color: black; border-right-style: double; border-left-style: double;
            border-right-color: black;">
            <tr>
                <td style="height: 30px; vertical-align: top">
                    Viewing Computer:&nbsp; <span id="VCName" style="cursor: text; position: absolute;
                        visibility: visible; top: 5px; left: 120px;" onmouseover="italics" onmouseout="normal"
                        onmousedown="VCNameChange"></span>
                    <input type="text" name="strTargetPC" style="position: absolute; visibility: hidden;
                        top: 4px; left: 120px; width: 150px; color: black; border-top-style: none; font-family: Arial;
                        border-right-style: none; border-left-style: none; height: auto; border-bottom-style: none;"
                        onblur="testNewVal">
                </td>
                <td style="height: 30px; vertical-align: top;">
                    :&nbsp;</td>
                <td style="height: 30px; vertical-align: top;">
                    Status: &nbsp;</td>
            </tr>
            <tr>
                <td style="height: 20px; width: 280px;">
                </td>
                <td style="height: 20px">
                </td>
                <td style="height: 20px">
                    IP Address: &nbsp;</td>
            </tr>
        </table>
        <table style="width: 100%; border-collapse: collapse;">
            <tr>
                <td class="tabHeaderSelectedCell" style="width: 289px">
                   


                        BIOS Info
                   

                </td>
                <td class="tabHeaderNotSelectedCell">
                   

                        Accounts
                   

                </td>
                <td class="tabHeaderNotSelectedCell">
                   

                        Other
                   

                </td>
            </tr>
            <tr>
                <td colspan="3" style="border-left-color: black; border-bottom-color: black; border-right-style: solid;
                    border-left-style: solid; background-color: #778899; border-right-color: black;
                    border-bottom-style: solid">
                   

                   

                       

                        <textarea id="VCBIOS" style="width: 98%; display: block; overflow: auto; border-top-style: none;
                            border-bottom-style: none; border-right-style: none; border-left-style: none;
                            background-color: #778899" rows="3" tabindex="1">
                        </textarea>
                       

                   

                   

                       

                           

                                User ID:

                                <input id="txtAddUserID" type="text" tabindex="3" style="width: 220px" />

                                <input name="rbScope" type="radio" value="Domain" checked="checked" />Domain
                                <input name="rbScope" type="radio" value="Local" />Local
                           

                           

                                Remove:

                               
                           

                           

                                Export:

                                <input id="txtExportTo" type="text" tabindex="6" style="width: 220px" />
                           

                           

                                Import:

                                <input id="txtImportFrom" type="text" tabindex="7" style="width: 220px" />

                               
                           

                       

                        <table style="color: black; border-collapse: collapse;">
                            <tr>
                                <td style="width: 150px;">
                                    User Accounts:</td>
                                <td style="width: 10px;">
                                </td>
                                <td style="width: 40px;">
                                    Action:</td>
                                <td id="tdAddHeader" onclick="showOptions(0)" style="width: 50px;" class="funcHeader" >
                                    Add</td>
                                <td style="width: 10px;">
                                </td>
                            </tr>
                            <tr>
                                <td rowspan="4" style="width: 150px; vertical-align: top;">
                                   
                                </td>
                                <td style="width: 10px;">
                                </td>
                                <td style="width: 40px;">
                                </td>
                                <td id="tdRemoveHeader" onclick="showOptions(1)" style="width: 50px;" class="funcHeader" >
                                    Remove</td>
                                <td style="width: 10px;">
                                </td>
                            </tr>
                            <tr>
                                <td style="width: 10px;">
                                </td>
                                <td style="width: 40px;">
                                </td>
                                <td id="tdExportHeader" onclick="showOptions(2)" style="width: 50px;" class="funcHeader" >
                                    Export</td>
                                <td style="width: 10px;">
                                </td>
                            </tr>
                            <tr>
                                <td style="width: 10px;">
                                </td>
                                <td style="width: 40px;">
                                </td>
                                <td id="tdImportHeader" onclick="showOptions(3)" style="width: 50px;" class="funcHeader" >
                                    Import</td>
                                <td style="width: 10px;">
                                </td>
                            </tr>
                            <tr>
                                <td style="width: 10px;">
                                </td>
                                <td style="width: 40px;">
                                </td>
                                <td style="width: 50px;">
                                </td>
                                <td style="width: 10px;">
                                </td>
                            </tr>
                            <tr>
                                <td id="paramAdd" style="width: 150px">
                                    Account Logged on:</td>
                                <td style="width: 10px">
                                </td>
                                <td style="width: 40px">
                                </td>
                                <td style="width: 50px">
                                </td>
                                <td style="width: 10px">
                                </td>
                            </tr>
                            <tr>
                                <td style="width: 150px">
                                   
                                </td>
                                <td style="width: 10px">
                                </td>
                                <td style="width: 40px">
                                </td>
                                <td style="width: 50px">
                                </td>
                                <td style="width: 10px">
                                </td>
                            </tr>
                        </table>
                       

                        <table style="border-collapse: collapse; width: 98%; color: black;">
                            <tr>
                                <td>
                                    Viewing Account:</td>
                                <td id="vcUserID" style="text-align: left" >
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Account SID:</td>
                                <td id="vcUserSid" style="text-align: left">
                                   
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Account Printers:</td>
                                <td>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" >
                                    <textarea id="PrinterInfo" style="width: 85%; display: block; overflow: auto; border-top-style: none;
                                        border-bottom-style: none; border-right-style: none; border-left-style: none;
                                        background-color: #778899; height: 75px;" tabindex="5"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Account Drives:</td>
                                <td>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" >
                                    <textarea id="DriveInfo" style="width: 85%; display: block; overflow: auto; border-top-style: none;
                                        border-bottom-style: none; border-right-style: none; border-left-style: none;
                                        background-color: #778899; height: 75px;" tabindex="5"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td style="width: 100px">
                                    Novell Data:</td>
                                <td>
                                   
                                </td>
                            </tr>
                            <tr style="display:none">
                                <td style="width: 100px">
                                    Profile Folders:</td>
                                <td>
                                    Table</td>
                            </tr>
                            <tr style="display:none">
                                <td style="width: 100px">
                                    Applications:</td>
                                <td>
                                    Table</td>
                            </tr>
                        </table>
                       

                   

                   

                       

                        Connect with Remote Desktop: &nbsp;&nbsp;&nbsp;<span id="VCLink" onclick="launch"
                            onmouseover="link" onmouseout="linkNormal"></span>
                       

                       

                        <table >
                            <tr>
                                <td style="width: 400px" >
                                    <table style="clear: none; border-collapse: collapse">
                                        <tr>
                                            <td style="width: 200px">
                                                <input name="rbAction" id="rbAction" type="radio" value="Remove" onclick="vcAction(Me)">
                                                Remove this PC from domain.
                                            </td>
                                            <td style="width: 200px">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 200px">
                                                <input name="rbAction" id="rbAction" type="radio" value="Rename" onclick="vcAction(Me)">
                                                Rename this computer.
                                            </td>
                                            <td style="width: 200px">
                                            </td>
                                        </tr>
                                        <tr id="renameRow" style="display:none;">
                                            <td style="width: 200px; text-align: right;">
                                                Rename to:
                                            </td>
                                            <td style="width: 200px">
                                                <input id="strNewPCName" type="text" style="width: 180px" onkeypress="checkKey(Me)">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 200px">
                                                <input name="rbAction" id="rbAction" type="radio" value="Add" onclick="vcAction(Me)">
                                                Add this computer to domain.
                                            </td>
                                            <td style="width: 200px">
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                                <td id="adminInfo" style="display: none; vertical-align: top; width: 300px;">
                                    <table style="clear: none; border-collapse: collapse">
                                        <tr>
                                            <td style="width: 130px">
                                                Admin Username :
                                            </td>
                                            <td style="width: 190px">
                                                <input id="strAdminID" type="text" style="width: 180px" onkeypress="checkKey(Me)">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="width: 130px">
                                                Admin Password :
                                            </td>
                                            <td style="width: 190px">
                                                <input id="strAdminPW" type="password" style="width: 180px" onkeypress="checkKey(Me)">
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                       

                       

                        Recent Migrations:

                       
                       

                        <!--<script language="VBScript">document.write(lastPCPath)</script>-->
                       

                   

                </td>
            </tr>
        </table>
    </form>
</body>
</html>

 

by: PilzberryFroBoyPosted on 2009-04-16 at 22:54:46ID: 24165133

Again, thank you to all the folks that have posted code.  There's so many, I can't even remember where I got code from, in addition to all the custom coding I had to do... but it's a big thanks to Rob for posting the conversion function from byte to string.

 

by: RobSampsonPosted on 2009-04-16 at 23:17:57ID: 24165223

Well I must say, that's an impressive HTA!  Nice work!

Mine is a lot simpler than, and doesn't provide half the functionality, but I've split my export into a HTA, and my Import into just a vbscript.

The export HTA will backup the ProfileList registry key, and the user profile with XCopy, so that the permissions are kept during the copy.

The export HTA is below.....The Import script will follow......

<head>
	<title>Export Profiles And ProfileList Reg Keys</title>
	<HTA:APPLICATION 
	     APPLICATIONNAME="Export Profiles And ProfileList Reg Keys"
	     SCROLL="no"
	     SINGLEINSTANCE="yes"
	     WINDOWSTATE="maximize"
	>
 
	<script language='vbscript'>
	Dim strHTAPath, intProfileCount
	Const FOF_CREATEPROGRESSDLG = &H10&
	
	<!--
		'*************************************************************
		'*************************************************************
		'********** EXAMPLE: DYNAMICALLY CREATE CHECKBOXES ***********
	
	'		span_inventoryoptions.InnerHTML = ""
	'		
	'		For i = 1 to 5
	'           span_inventoryoptions.InnerHTML = span_inventoryoptions.InnerHTML &_
	'            "<input type='checkbox' name='Option" & i & "' value='" & i & "' checked=True> Checkbox " & i &_
	'			"<BR>"
	'		Next
	'		
	'		Msgbox "Name:" & Option1.Name & " Value: " & Option1.Value & vbCrLF &_
	'				"Name:" & Option2.Name & " Value: " & Option2.Value & vbCrLF &_
	'				"Name:" & Option3.Name & " Value: " & Option3.Value & vbCrLF &_
	'				"Name:" & Option4.Name & " Value: " & Option4.Value & vbCrLF &_
	'				"Name:" & Option5.Name & " Value: " & Option5.Value & vbCrLF
	
		'*************************************************************
		'*************************************************************
		'*************************************************************
	
	    Sub Window_OnLoad
 
			Dim objFSO
 
			If Mid(document.location, 6, 3) = "///" Then
				strHTAPath = Mid(Replace(Replace(document.location, "%20", " "), "/", "\"), 9)
			Else
				strHTAPath = Mid(Replace(Replace(document.location, "%20", " "), "/", "\"), 6)
			End If
			
			Set objNetwork = CreateObject("WScript.Network")
			
			Create_ProfileList_Options
	    End Sub
		
		'*************************************************************
		'*************************************************************
		
		Sub Create_ProfileList_Options
		
			Dim objFSO
			Const intForReading = 1
			
			'Reset software options counter back to zero
			intProfileCount = 0
			
			Set objFSO = CreateObject("Scripting.FileSystemObject")
			strRoot = "C:\Documents and Settings"
			strProfilePaths = ""
			For Each objFolder In objFSO.GetFolder(strRoot).SubFolders
				strFoldername = LCase(objFolder.Name)
				strDateLastModified = objFolder.DateLastModified
				If strFoldername <> "administrator" And _
				strFoldername <> "all users" And _
				InStr(strFoldername, "default user") = 0 And _
				strFoldername <> "localservice" And _
				strFoldername <> "networkservice" Then
					If DateDiff("d", CDate(strDateLastModified), Now) <= 90 Then
						If strProfilePaths = "" Then
							strProfilePaths = objFolder.Name & ";" & objFolder.Path & ";" & strDateLastModified
						Else
							strProfilePaths = strProfilePaths & VbCrLf & objFolder.Name & ";" & objFolder.Path & ";" & strDateLastModified
						End If
					End If
				End If
				
			Next
			arrOptions = Split(strProfilePaths, VbCrLf)
			intProfileCount = UBound(arrOptions)
			strOptions = "<table>"
			For intCurrentOption = 0 To intProfileCount
				strFolderName = Split(arrOptions(intCurrentOption), ";")(0)
				strFolderPath = Split(arrOptions(intCurrentOption), ";")(1)
				strDateLastModified = Split(arrOptions(intCurrentOption), ";")(2)
				strOptions = strOptions & _
					"<tr><td width='50%'><input type='checkbox' id='chkOption" & intCurrentOption & "' " & _
					"name='" & strFolderName & "' value='" & strFolderPath & "' " & _
					"checked=True>" & strFolderName & "</td><td>Last modified: " & strDateLastModified & "</td></tr>"
			Next
			strOptions = strOptions & "</table>"
			spanInventoryOptions.InnerHTML = strOptions
 
 
		End Sub
	    
		'*************************************************************
	   	'*************************************************************
		
		Sub Export_Selected_Profiles
			
			Const HKEY_LOCAL_MACHINE = &H80000002
	
			Disable_Buttons
			
			intOptionsSelected = 0
			
			'******** Count amount of selected options so we know how big to make the array ********
			For intCurrentOption = 0 To intProfileCount
				strOptionChecked = "chkOption" & intCurrentOption & ".Checked"
				If Eval(strOptionChecked) = True Then
					intOptionsSelected = intOptionsSelected + 1
				End If
			Next
			
			'***************************** Make sure at least one is selected **********************
			If intOptionsSelected < 1 Then
				MsgBox "No profiles have been selected. Select a profile to export.", VBOkOnly, "Profile"
				Enable_Buttons
				Exit Sub
			End If
			
			Set objShell = CreateObject("WScript.Shell")
			Set objNetwork = CreateObject("WScript.Network")
			Set objShellApp = CreateObject("Shell.Application")
			Set objFSO = CreateObject("Scripting.FileSystemObject")
			Const intForReading = 1
			strBackupLocation = "C:\DUMMY\FOLDER\DUMMY\FOLDER"
			strResponse = vbNo
			While objFSO.FolderExists(strBackupLocation) = False And strBackupLocation <> "" And strResponse <> vbYes
				strBackupLocation = InputBox("Enter backup path to back up the profile registry keys to:", "Backup Location", "\\backupserver\pc_refresh\" & objNetwork.ComputerName)
				If strBackupLocation <> "" And InStr(LCase(strBackupLocation), LCase(objNetwork.ComputerName)) = 0 Then
					strResponse = MsgBox("The backup location you have specified does not contain the computer name." & VbCrLf & _
						"Are you sure you want to back files up to this location:" & VbCrLf & strBackupLocation, vbYesNo, "Continue?")
				Else
					strResponse = vbYes
				End If
				If strBackupLocation <> "" And objFSO.FolderExists(objFSO.GetParentFolderName(strBackupLocation)) = False Then
					MsgBox objFSO.GetParentFolderName(strBackupLocation) & VbCrLf & "does not exist. Please specify a path where the parent folder exists."
					strResponse = vbNo
				End If
			Wend
			If strBackupLocation = "" Then
				MsgBox "Profile export cancelled."
			Else
				If Right(strBackupLocation, 1) = "\" Then strBackupLocation = Left(strBackupLocation, Len(strBackupLocation) - 1)
				If objFSO.FolderExists(strBackupLocation) = False Then objFSO.CreateFolder strBackupLocation
				If Right(strBackupLocation, 1) = "\" Then strBackupLocation = Left(strBackupLocation, Len(strBackupLocation) - 1)
				strBackupLocation = strBackupLocation & "\Profiles"
				If objFSO.FolderExists(strBackupLocation) = False Then objFSO.CreateFolder strBackupLocation
				
				'***************** Fill the Options array with the Names and Values *******************
				For intCurrentOption = 0 To intProfileCount
					strOptionChecked = "chkOption" & intCurrentOption & ".Checked"
					If Eval(strOptionChecked) = True Then
						'strUsername = InputBox("Enter the username you wish to find the SID for:", "Username", strUsername)
						strUsername = Eval("chkOption" & intCurrentOption & ".Name")
						strFolderPath = Eval("chkOption" & intCurrentOption & ".Value")
						strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adsPath")
						If Left(strUserADsPath, 7) <> "LDAP://" Then
							strUsername = InputBox("Unable to find adsPath for " & strUsername & "." & VbCrLf & _
								"If the user has a different username, please enter it:", "Alternate username")
							If strUsername <> "" Then strUserADsPath = Get_LDAP_User_Properties("user", "samAccountName", strUsername, "adsPath")
						End If
						If Left(strUserADsPath, 7) = "LDAP://" Then
							Set objUser = GetObject(strUserADsPath)
							arrSid = objUser.objectSid
							strSidHex = OctetToHexStr(arrSid)
							strSidDec = HexStrToDecStr(strSidHex)
							'InputBox "The SID for " & objUser.samAccountName & " is in the variable strSidDec and is below:", "Title", strSidDec
							strRegKey = "HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & strSidDec
							On Error Resume Next
							' Test if the SID root key is there
							strProfileImagePath = objShell.RegRead(strRegKey & "\ProfileImagePath")
							If Err.Number <> 0 Then
								Err.Clear
								On Error GoTo 0
								MsgBox "Could not find " & strRegKey
							Else
								On Error GoTo 0
								strProfileImagePath = Replace(LCase(strProfileImagePath), "%systemdrive%", objShell.ExpandEnvironmentStrings("%SYSTEMDRIVE%"))
								If objFSO.FolderExists(strBackupLocation) = False Then objFSO.CreateFolder strBackupLocation
								objShell.Run "reg export """ & strRegkey & """ """ & strBackupLocation & "\Profile_Keys_For_" & strUsername & ".reg""", 0, True
								'MsgBox "Profile Keys have been backed up to " & strBackupLocation
								If Right(strBackupLocation, 1) <> "\" Then strBackupLocation = strBackupLocation & "\"
								If objFSO.FolderExists(strBackupLocation & strUserName) = False Then objFSO.CreateFolder strBackupLocation & strUserName
								strExcludeFile = Left(strHTAPath, InStrRev(strHTAPath, "\")) & "ExcludedFolders.txt"
								Set objExclude = objFSO.CreateTextFile(strExcludeFile, True)
								objExclude.WriteLine "\local settings\temporary internet files\"
								objExclude.WriteLine "\local settings\temp\"
								objExclude.Close
								Set objExclude = Nothing
								strCommand = "cmd /c xcopy " & objFSO.GetFolder(strFolderPath).ShortPath & " """ & strBackupLocation & strUserName & "\"" /exclude:" & objFSO.GetFile(strExcludeFile).ShortPath & " /e /c /h /r /k /x /y"
								objShell.Run strCommand, 1, True
								objFSO.DeleteFile strExcludeFile, True
								
								'MsgBox "User Profile has been backed up to " & strBackupLocation
							End If
						Else
							MsgBox "Could not find adsPath for " & strUsername
						End If
					End If
				Next
				
				'Now copy All Users "Desktop" and "Start Menu\Programs\Startup" shortcuts
				If objFSO.FolderExists(strBackupLocation & "All Users") = False Then objFSO.CreateFolder strBackupLocation & "All Users"
				If objFSO.FolderExists(strBackupLocation & "All Users\Desktop") = False Then objFSO.CreateFolder strBackupLocation & "All Users\Desktop"
				If objFSO.FolderExists(strBackupLocation & "All Users\Start Menu") = False Then objFSO.CreateFolder strBackupLocation & "All Users\Start Menu"
				If objFSO.FolderExists(strBackupLocation & "All Users\Start Menu\Programs") = False Then objFSO.CreateFolder strBackupLocation & "All Users\Start Menu\Programs"
				If objFSO.FolderExists(strBackupLocation & "All Users\Start Menu\Programs\Startup") = False Then objFSO.CreateFolder strBackupLocation & "All Users\Start Menu\Programs\Startup"
				strCommand = "cmd /c xcopy " & objFSO.GetFolder("C:\Documents and Settings\All Users\Desktop").ShortPath & "\*.* """ & strBackupLocation & "All Users\Desktop\"" /c /h /r /k /x /y"
				objShell.Run strCommand, 0, True
				strCommand = "cmd /c xcopy " & objFSO.GetFolder("C:\Documents and Settings\All Users\Start Menu\Programs\Startup").ShortPath & "\*.* """ & strBackupLocation & "All Users\Start Menu\Programs\Startup\"" /c /h /r /k /x /y"
				objShell.Run strCommand, 0, True
				'objFSO.CopyFile "C:\Documents and Settings\All Users\Desktop\*", strBackupLocation & "All Users\Desktop\", True
				'objFSO.CopyFile "C:\Documents and Settings\All Users\Start Menu\Programs\Startup\*", strBackupLocation & "All Users\Start Menu\Programs\Startup\", True
				
				'MsgBox "The selected profiles have been backed up to " & strBackupLocation
				spanProgressData.InnerHTML = "The selected profiles have been backed up to " & strBackupLocation
				
				spanProgressData.InnerHTML = spanProgressData.InnerHTML & "<BR>Windows fonts have been backed up to " & Left(strBackupLocation, InStrRev(strBackupLocation, "\") - 1) & "\Windows_Fonts\"
				spanProgressData.InnerHTML = spanProgressData.InnerHTML & "<BR><BR>Finished!"
				'************ Check each machine that is selected, and check for software *************
			End If
			
			Enable_Buttons
			
		End Sub
		
		'*************************************************************
 
	    Sub Enable_Buttons
	    End Sub
	
		'*************************************************************
	    
	    Sub Disable_Buttons
	    End Sub
	
		'*************************************************************
		Sub HTASleep(intSeconds)
			Set objShell = CreateObject("WScript.Shell")
			objShell.Run "ping 127.0.0.1 -n " & intSeconds + 1, 0, True
		End Sub
		'*************************************************************
 
'Working VBScript Active Directory Binary SID conversion to String SID
' Source: http://forums.techarena.in/showthread.php?t=588078
'Function to convert OctetString (byte array) to Hex string.
Function OctetToHexStr(arrbytOctet)
Dim k
OctetToHexStr = ""
For k = 1 To Lenb(arrbytOctet)
OctetToHexStr = OctetToHexStr & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
Next
End Function
 
Function HexStrToDecStr(strSid)
' Function to convert Hex string Sid to Decimal string (SDDL) Sid.
 
 
' SID anatomy:
' Byte Position
' 0 : SID Structure Revision Level (SRL)
' 1 : Number of Subauthority/Relative Identifier
' 2-7 : Identifier Authority Value (IAV) [48 bits]
' 8-x : Variable number of Subauthority or Relative Identifier (RID) [32 bits]
'
' Example:
'
' <Domain/Machine>\Administrator
' Pos : 0 | 1 | 2 3 4 5 6 7 | 8 9 10 11 | 12 13 14 15 | 16 17 18 19 | 20 21 22 23 | 24 25 26 27
' Value: 01 | 05 | 00 00 00 00 00 05 | 15 00 00 00 | 06 4E 7D 7F | 11 57 56 7A | 04 11 C5 20 | F4 01 00 00
' str : S- 1 | | -5 | -21 | -2138918406 | -2052478737 | -549785860 | -500
 
 
Const BYTES_IN_32BITS = 4
Const SRL_BYTE = 0
Const IAV_START_BYTE = 2
Const IAV_END_BYTE = 7
Const RID_START_BYTE = 8
Const MSB = 3 'Most significant byte
Const LSB = 0 'Least significant byte
 
 
Dim arrbytSid, lngTemp, base, offset, i
 
 
ReDim arrbytSid(Len(strSid)/2 - 1)
 
 
' Convert hex string into integer Array
For i = 0 To UBound(arrbytSid)
      arrbytSid(i) = CInt("&H" & Mid(strSid, 2 * i + 1, 2))
Next
 
 
' Add SRL number
HexStrToDecStr = "S-" & arrbytSid(SRL_BYTE)
 
 
' Add Identifier Authority Value
lngTemp = 0
For i = IAV_START_BYTE To IAV_END_BYTE
      lngTemp = lngTemp * 256 + arrbytSid(i)
Next
HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
 
 
' Add a variable number of 32-bit subauthority or
' relative identifier (RID) values.
' Bytes are in reverse significant order.
' i.e. HEX 01 02 03 04 => HEX 04 03 02 01
' = (((0 * 256 + 04) * 256 + 03) * 256 + 02) * 256 + 01
' = DEC 67305985
For base = RID_START_BYTE To UBound(arrbytSid) Step BYTES_IN_32BITS
      lngTemp = 0
      For offset = MSB to LSB Step -1
            lngTemp = lngTemp * 256 + arrbytSid(base + offset)
      Next
      HexStrToDecStr = HexStrToDecStr & "-" & CStr(lngTemp)
Next
End Function ' HexStrToDecStr
 
Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)
      
      ' This is a custom function that connects to the Active Directory, and returns the specific
      ' Active Directory attribute value, of a specific Object.
      ' strObjectType: usually "User" or "Computer"
      ' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
      '				It filters the results by the value of strObjectToGet
      ' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
      '				For example, if you are searching based on the user account name, strSearchField
      '				would be "samAccountName", and strObjectToGet would be that speicific account name,
      '				such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
      '	strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
      '				the home folder path, as defined by the AD, for a specific user, this would be
      '				"homeDirectory".  If you want to return the ADsPath so that you can bind to that
      '				user and get your own parameters from them, then use "ADsPath" as a return string,
      '				then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)
      
      ' Now we're checking if the user account passed may have a domain already specified,
      ' in which case we connect to that domain in AD, instead of the default one.
      If InStr(strObjectToGet, "\") > 0 Then
            arrGroupBits = Split(strObjectToGet, "\")
            strDC = arrGroupBits(0)
            strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
            strObjectToGet = arrGroupBits(1)
      Else
      ' Otherwise we just connect to the default domain
            Set objRootDSE = GetObject("LDAP://RootDSE")
            strDNSDomain = objRootDSE.Get("defaultNamingContext")
      End If
 
      strBase = "<LDAP://" & strDNSDomain & ">"
      ' Setup ADO objects.
      Set adoCommand = CreateObject("ADODB.Command")
      Set adoConnection = CreateObject("ADODB.Connection")
      adoConnection.Provider = "ADsDSOObject"
      adoConnection.Open "Active Directory Provider"
      adoCommand.ActiveConnection = adoConnection
 
 
      ' Filter on user objects.
      'strFilter = "(&(objectCategory=person)(objectClass=user))"
      strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"
 
      ' Comma delimited list of attribute values to retrieve.
      strAttributes = strCommaDelimProps
      arrProperties = Split(strCommaDelimProps, ",")
 
      ' Construct the LDAP syntax query.
      strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
      adoCommand.CommandText = strQuery
      ' Define the maximum records to return
      adoCommand.Properties("Page Size") = 100
      adoCommand.Properties("Timeout") = 30
      adoCommand.Properties("Cache Results") = False
 
      ' Run the query.
      Set adoRecordset = adoCommand.Execute
      ' Enumerate the resulting recordset.
      strReturnVal = ""
      Do Until adoRecordset.EOF
          ' Retrieve values and display.    
          For intCount = LBound(arrProperties) To UBound(arrProperties)
                If strReturnVal = "" Then
                      strReturnVal = adoRecordset.Fields(intCount).Value
                Else
                      strReturnVal = strReturnVal & VbCrLf & adoRecordset.Fields(intCount).Value
                End If
          Next
          ' Move to the next record in the recordset.
          adoRecordset.MoveNext
      Loop
 
      ' Clean up.
      adoRecordset.Close
      adoConnection.Close
      Get_LDAP_User_Properties = strReturnVal
 
End Function
	-->
	</script>
 
</head>
 
<body>
 
	<table width='80%' align='center' border='0'>
		<tr>
			<td align='center'>
			</td>
		</tr>
	</table>
	<br><br><br>
	<table width='80%' height='90%' align='center' border='0'>
		<tr height='20%'>
			<td colspan=3 align='center'>
				<font face='Arial' size='8'><u>Export Profiles And ProfileList Reg Keys</u></font>
			</td>
		</tr>
		<tr>
			<td>
				<font face='Arial' size='4'>Available Profiles</font>
			</td>
		</tr>
		<tr>
			<td width='33.4%'>
				<font face='Arial' size='3'><span id='spanInventoryOptions'></span></font>
			</td>
		</tr>
		<tr>
			<td>
				<input type='button' value='Export Selected Profiles' name='btnExportProfiles'  onClick='vbs:Export_Selected_Profiles'>
			</td>
		</tr>
		<tr height='20%'>
			<td colspan=3 align='center'>
				<font face='Arial' size='3'><span id = 'spanProgressData'></span></font>
			</td>
		</tr>
	</table>
 
</body>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:

Select allOpen in new window

 

by: RobSampsonPosted on 2009-04-16 at 23:20:24ID: 24165237

The Import script just imports the reg keys again, and perfoms an XCopy to copy the profile back with permissions.

I forgot to mention, the export excludes the Local Settings\Temporary Internet Files and the Local Settings\Temp folders.

Regards,

Rob.

'MsgBox "Ask for location, then check for REG files, and import."
Set objShellApp = CreateObject("Shell.Application")
Const FOF_CREATEPROGRESSDLG = &H10&
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
strBackupLocation = "C:\DUMMY\FOLDER\DUMMY\FOLDER"
boolRegFilesFound = False
While objFSO.FolderExists(strBackupLocation) = False And boolRegFilesFound = False And strBackupLocation <> ""
	strBackupLocation = InputBox("Enter the folder path where profiles were backed up to, which contains the user profiles from the old computer:", "Restore Location", "\\backupserver\pc_refresh\<OLDCOMPUTERNAME>")
	If objFSO.FolderExists(strBackupLocation) = True Then
		If Right(strBackupLocation, 1) = "\" Then strBackupLocation = Left(strBackupLocation, Len(strBackupLocation) - 1)
		If objFSO.FolderExists(strBackupLocation) = False Then
			MsgBox "Unable to find " & strBackupLocation
		Else
			strBackupLocation = strBackupLocation & "\Profiles"
			boolRegFilesFound = False
			For Each objFile In objFSO.GetFolder(strBackupLocation).Files
				If Right(LCase(objFile.Name), 4) = ".reg" Then
					boolRegFilesFound = True
					Exit For
				End If
			Next
			If boolRegFilesFound = False Then
				MsgBox "No reg files were found in " & strBackupLocation & VbCrLf & "Please make sure you have backed up profiles correctly."
				strBackupLocation = "C:\DUMMY\FOLDER\DUMMY\FOLDER"
			End If
		End If
	End If
Wend
If strBackupLocation = "" Then
	MsgBox "Restore operation cancelled."
Else
	If Right(strBackupLocation, 1) = "\" Then strBackupLocation = Left(strBackupLocation, Len(strBackupLocation) - 1)
	For Each objFile In objFSO.GetFolder(strBackupLocation).Files
		If Right(LCase(objFile.Name), 4) = ".reg" Then
			objShell.Run "regedit /s """ & objFile.Path & """", 1, True
		End If
	Next	
	For Each objFolder In objFSO.GetFolder(strBackupLocation).SubFolders
		'Set objTargetFolder = objShellApp.NameSpace("C:\Documents and Settings")
		'objTargetFolder.CopyHere objFolder.Path, FOF_CREATEPROGRESSDLG
		objShell.Run "cmd /c xcopy " & objFolder.ShortPath & " ""C:\Documents and Settings\" & objFolder.Name & """ /i /e /c /h /r /k /x /y", 1, True
	Next
	MsgBox "User Profiles have been restored from " & strBackupLocation
End If

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:

Select allOpen in new window

 

by: PilzberryFroBoyPosted on 2009-04-16 at 23:27:39ID: 24165269

LOL thanks.  Like I said ... what was it, like 9 months ago? ... It could be streamlined, I'm sure, but the functionality is there.  

The idea was that a desktop support person could carry a USB stick around with this HTA on it (because it creates a log.txt file, and uses it as a database), and export off the old machine.  Then install the new computer, and plug the USB stick back in, and would know where to go to get the previous user/computer/sid/path information to add to the newly created profile on the newly added machine.

Anyhow, thanks again.  Your function was a great help.

:)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...