The previous post had us run a script on a machine prior to it being replaced during an equipment refresh. This script follows that one and should be run on the new system.
Group Policy creates a mapping to the user's home directory using the z: drive as used below.
The following script maps drives based on the mappings gathered and placed in the mappings.csv file created in the previous post.
On Error Resume Next
Dim objNetwork
Dim strDriveLetter, strRemotePath
dim fs,objTextFile
dim arrStrset
Const ForReading = 1
boolPersistent = True
FileName = "z:\newsys\mappings.csv"
set fs = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
set objTextFile = fs.OpenTextFile(FileName, ForReading)
Do while NOT objTextFile.AtEndOfStream
arrStr = split(objTextFile.ReadLine,",")
drive = arrStr(0)
path = arrStr(1)
objNetwork.MapNetworkDrive drive, path, boolPersistent
Loop
objTextFile.Close
set objTextFile = Nothing
set fs = Nothing
WScript.Quit
Copy this script into notepad and save with a .vbs extension.
Wednesday, July 7, 2010
System Replacement Script
We have many users with special drive mappings that aren't being mapped in Group Policy - we're still in the Dark Ages in this respect.
Anyway, here's a little script that we run on a system prior to replacing it in our current system refresh:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDrives = objWMIService.ExecQuery _
("Select * From Win32_LogicalDisk Where DriveType = 4")
Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set OutPutFile = FileSystem.CreateTextFile("z:\newsys\mappings.csv", True)
For Each objDrive in colDrives
drive = objDrive.DeviceID
path = objDrive.ProviderName
OutPutFile.Write drive & "," & path & vbcrlf
Next
This script creates a .csv file in the user's home directory, mapped to z:, for later use.
In order to use this script, copy the code and paste it into notepad, saving the file with a .vbs extension.
In order to add it to a batch file, simply add the command cscript filename.vbs.
Anyway, here's a little script that we run on a system prior to replacing it in our current system refresh:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDrives = objWMIService.ExecQuery _
("Select * From Win32_LogicalDisk Where DriveType = 4")
Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
Set OutPutFile = FileSystem.CreateTextFile("z:\newsys\mappings.csv", True)
For Each objDrive in colDrives
drive = objDrive.DeviceID
path = objDrive.ProviderName
OutPutFile.Write drive & "," & path & vbcrlf
Next
This script creates a .csv file in the user's home directory, mapped to z:, for later use.
In order to use this script, copy the code and paste it into notepad, saving the file with a .vbs extension.
In order to add it to a batch file, simply add the command cscript filename.vbs.
New Windows 7 System Deployment
Some of you might be familiar with Windows 7 and the process of running a system rating and registering the system.
Currently, we are going through a system refresh and need to deploy a couple hundred Windows 7 systems. We used Ghost and created an image, imaged the machines, and Sysprepped them.
In order to deploy these machines, we decided we needed to automate as much of the process as possible, reducing the human error factor and ensuring no step is missed - although we do have a checklist that is to be completed with each system deployed.
We created a few batch files that make use of VBscript files and some freeware single file applications.
One of the steps when logging onto the system as an administrator after configuring network settings and joining the domain is to simply run the System Rating utility and register Windows 7. Fortunately, both of these utilities have command-line versions. We simply added these commands to a batch file, along with other useful commands, and have the tech run them during the installation process.
The commands are:
slmgr -ato
winsat formal
You can easily add these to your own batch files and hopefully save yourself some time and perform other important steps while these utilities run.
On occasion, we have seen the system rating suffer due to performing other tasks and need to re-run the system rating utility. This is extremely rare, however - maybe 5 out of 250 systems or so.
Currently, we are going through a system refresh and need to deploy a couple hundred Windows 7 systems. We used Ghost and created an image, imaged the machines, and Sysprepped them.
In order to deploy these machines, we decided we needed to automate as much of the process as possible, reducing the human error factor and ensuring no step is missed - although we do have a checklist that is to be completed with each system deployed.
We created a few batch files that make use of VBscript files and some freeware single file applications.
One of the steps when logging onto the system as an administrator after configuring network settings and joining the domain is to simply run the System Rating utility and register Windows 7. Fortunately, both of these utilities have command-line versions. We simply added these commands to a batch file, along with other useful commands, and have the tech run them during the installation process.
The commands are:
slmgr -ato
winsat formal
You can easily add these to your own batch files and hopefully save yourself some time and perform other important steps while these utilities run.
On occasion, we have seen the system rating suffer due to performing other tasks and need to re-run the system rating utility. This is extremely rare, however - maybe 5 out of 250 systems or so.
Script for Reseting Domain User Passwords
This script is useful for resetting an Active Directory user account password.
Copy the code into notepad, make necessary changes to reflect your domain and organizational units, change the number in the array to reflect the number of organizational units, and save with a .hta extension.
Note: the array amount starts counting at 0. Therefore if you have 5 organizational units, the array would be For i=0 to 4. Also, currently, this code resets a user's password to "P@ssw0rd."
I hope this helps.
Copy the code into notepad, make necessary changes to reflect your domain and organizational units, change the number in the array to reflect the number of organizational units, and save with a .hta extension.
Note: the array amount starts counting at 0. Therefore if you have 5 organizational units, the array would be For i=0 to 4. Also, currently, this code resets a user's password to "P@ssw0rd."
<head>
<title>Change Password</title>
<HTA:APPLICATION
APPLICATIONNAME="Change Password"
SCROLL="No"
SINGLEINSTANCE="yes"
WINDOWSTATE="normal"
MAXIMIZEBUTTON="no"
ICON="C:/iconlocation/icon.ico"
>
</head>
<script language="VBScript">
Sub Window_onLoad
window.resizeTo 400,250
strUserbox.Focus
End Sub
Sub Password
On Error Resume Next
Dim strUser
Dim objUser
Dim arrOU
Dim objRootDSE
Dim strDNSDomain
Dim errorVal
arrOU = Array("OU=Sales","OU=Admin","OU=Clerical","OU=Engineers","OU=Executive Staff","OU=Others","OU=More Others","OU=Trainees","OU=Temps")
strUser = struserbox.value
errorValue = 1
For i=0 to 8
Set objUser = GetObject("LDAP://sAMAccountName=" & strUser & ",OU=Users," & arrOU(i) & ",DC=domain,DC=com")
If Err.Number <> -2147016656 Then
errorValue = 0
End If
objUser.SetPassword("P@ssw0rd")
If changePass.Checked Then
objUser.Put "PwdLastSet", 0
objUser.SetInfo
End If
Set objUser = nothing
Next
If errorValue = 1 Then
Msgbox "Account does not exist: " & strUser
errorValue = 0
Else
Msgbox "Password for " & strUser & " has been reset."
End If
strUserbox.value = ""
strUserbox.Focus
changePass.checked=False
End Sub
Sub RunScript
If window.event.Keycode = 13 Then
call Password()
End If
End Sub
</script>
<body STYLE="font:14 pt arial; color:white;
filter:progid:DXImageTransform.Microsoft.Gradient
(GradientType=1, StartColorStr='#000000', EndColorStr='#0000FF')"onkeypress="RunScript">
<center>Enter Username: <P>
<input type="text" name="strUserbox" size="30"><P>
<input type="button" value=" OK " name="run_button" onClick="Password"><p>
<input type="checkbox" name="changePass"> Check this box to force a password change on next login.
</center>
</body>
I hope this helps.
An HTA Example for Mailbox Creation
Sometimes you have might want to make things a little easier for your coworkers to perform somewhat frequent tasks. This code uses VBscript and Powershell to create a mailbox in Exchange 2007.
In order for this code to work properly, besides editing the file to address your domain, server names, and Exchange 2007 database names, you will need to have a folder called FSO on your c: drive.
Note: Blogger has some limitations on how long the lines can be on the page and therefore uses word wrap. This means that you will have to remove those carriage returns from the code where necessary. It shouldn't be too difficult to see where two lines should have been one. Sorry if there's much confusion.
Another note: The user of this application still needs to be an exchange account administrator.
After creating the FSO folder on your c: drive, copy the above code into notepad, edit the necessary changes to address your environment (domain, Exchange server name, and database names) and save it with a .HTA extension.
This should get you off to a good start in making your own application to address your office's needs.
In order for this code to work properly, besides editing the file to address your domain, server names, and Exchange 2007 database names, you will need to have a folder called FSO on your c: drive.
Note: Blogger has some limitations on how long the lines can be on the page and therefore uses word wrap. This means that you will have to remove those carriage returns from the code where necessary. It shouldn't be too difficult to see where two lines should have been one. Sorry if there's much confusion.
Another note: The user of this application still needs to be an exchange account administrator.
<HTML>
<Head>
<title>Mailbox Creation Utility</title>
<HTA:APPLICATION
ID="Mailbox Creation Utility"
APPLICATIONNAME="Mailbox Creation Utility"
SCROLL="No"
SINGLEINSTANCE="yes"
ICON="c:/FSO/mailbox.ico"
>
</Head>
<script language="vbscript">
Sub Window_OnLoad
self.ResizeTo 315,575
End Sub
Sub ReloadBtn_OnClick
Location.Reload(True)
End Sub
Sub btnok_onClick
FName = txtFName.value
LName = txtLName.value
Alias = txtAlias.value
strDatabase = ""
Title = txtTitle.value
If DeleteCheckbox.Checked Then
Delete
Else
If HideCheckbox.Checked Then
Hide
Else
If UnhideCheckbox.Checked Then
Unhide
Else
If Alias = "" Then
Alias = Left(FName, 1) + LName
End If
If UserOption(0).Checked Then
strDatabase = "mailserver\PrimaryA Mailbox Database"
End If
If UserOption(1).Checked Then
strDatabase = "mailserver\PrimaryB Mailbox Database"
End If
If strDatabase = "" Then
Msgbox "Please select the appropriate database."
Else If strDatabase <> "" Then
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\FSO\mailbox.ps1", True)
path = filesys.GetAbsolutePathName("c:\FSO\Mailbox.ps1")
getname = filesys.GetFileName(path)
intAlias = Len(Alias)
AliasFLetter = UCase(Left(Alias, 2))
AliasRestLetters = LCase(Right(Alias, intAlias -2))
Alias = AliasFLetter & AliasRestLetters
filetxt.WriteLine("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin")
filetxt.WriteLine("$usertest = get-user -Identity " & chr(34) & LName & ", " & FName & chr(34) & " |select RecipientType")
filetxt.WriteLine("if " & chr(40) & "$usertest.RecipientType -eq " & chr(34) & "userMailbox" & chr(34) & chr(41))
filetxt.WriteLine("{Write-Host " & chr(34) & "The mailbox already exists." & chr(34) & " -foregroundcolor red}")
filetxt.WriteLine("Else {")
filetxt.WriteLine("enable-mailbox " & chr(34) & LName & ", " & FName & chr(34) & " -Database " & chr(34) & strDatabase & chr(34))
filetxt.WriteLine("Start-Sleep -s 15")
filetxt.WriteLine("set-user " & chr(34) & LName & ", " & FName & chr(34) & " -title " & chr(34) & Title & chr(34) & " -Company " &
chr(34) & "Some Sales Office" & chr(34))
filetxt.WriteLine("get-mailbox " & chr(34) & LName & ", " & FName & chr(34) & " | set-mailbox -Alias " & Alias & " -MaxSendSize 5mb
-MaxReceiveSize 5mb | add-distributiongroupmember -Id " & chr(34) & "DACRIM E-Mail - All" & chr(34))
filetxt.WriteLine("set-CASMailbox " & chr(34) & LName & ", " & FName & chr(34) & " -ActiveSyncEnabled:$False")
filetxt.WriteLine("get-mailbox " & chr(34) & LName & ", " & FName & chr(34) & " | Add-mailboxpermission -accessrights fullaccess
-user domain\administrator")
filetxt.WriteLine("get-mailbox " & chr(34) & LName & ", " & FName & chr(34) & " | Add-mailboxpermission -accessrights fullaccess
-user domain\BESAdmin")
if CreateHiddenCheckbox.checked Then
filetxt.WriteLine("Set-Mailbox -identity " & chr(34) & LName & ", " & FName & chr(34) & "
-HiddenFromAddressListsEnabled $true")
End If
filetxt.WriteLine("}")
filetxt.Close
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\FSO\mailbox.ps1")
Location.Reload(True)
End If
End If
End If
End If
End If
End Sub
Sub Delete
FName = txtFName.value
LName = txtLName.value
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\FSO\mailbox.ps1", True)
path = filesys.GetAbsolutePathName("c:\FSO\Mailbox.ps1")
getname = filesys.GetFileName(path)
filetxt.WriteLine("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin")
filetxt.WriteLine("disable-mailbox -identity " & chr(34) & LName & ", " & FName & chr(34) & " -confirm:$false")
filetxt.Close
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\FSO\mailbox.ps1")
Location.Reload(True)
End Sub
Sub Hide
FName = txtFName.value
LName = txtLName.value
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\FSO\mailbox.ps1", True)
path = filesys.GetAbsolutePathName("c:\FSO\Mailbox.ps1")
getname = filesys.GetFileName(path)
filetxt.WriteLine("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin")
filetxt.WriteLine("Set-Mailbox -identity " & chr(34) & LName & ", " & FName & chr(34) & " -HiddenFromAddressListsEnabled $true")
filetxt.Close
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\FSO\mailbox.ps1")
Location.Reload(True)
End Sub
Sub Unhide
FName = txtFName.value
LName = txtLName.value
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.CreateTextFile("c:\FSO\mailbox.ps1", True)
path = filesys.GetAbsolutePathName("c:\FSO\Mailbox.ps1")
getname = filesys.GetFileName(path)
filetxt.WriteLine("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin")
filetxt.WriteLine("Set-Mailbox -identity " & chr(34) & LName & ", " & FName & chr(34) & " -HiddenFromAddressListsEnabled $false")
filetxt.Close
Set objShell = CreateObject("Wscript.Shell")
objShell.Run("powershell.exe -noexit c:\FSO\mailbox.ps1")
Location.Reload(True)
End Sub
</script>
<body BGCOLOR=DFDFDF background="c:\fso\mailbox1.jpg" STYLE="background-repeat: no-repeat;=background-position: center;" >
<center><b><font size=5>Mailbox Creation Utility</font></center>
<HR>
<br><input type="checkbox"name="CreateHiddenCheckbox"value="1"> Create Hidden
<br><input type="checkbox"name="HideCheckbox"value="2"> Hide Existing Mailbox
<br><input type="checkbox"name="UnhideCheckbox"value="3"> Unhide Mailbox
<br><input type="checkbox"name="DeleteCheckbox"value="4"> Delete Mailbox
<p> First Name: <input id="txtFName" type="text" name="txtFName" size="20">
<p> Last Name: <input id="txtLName" type="text" name="txtLName" size="20">
<p>Alias: <input id="txtAlias" type="text" name="txtAlias" size="8">
<p> Title: <input id="txtTitle" type="text" name="txtTitle" size="27">
<p>Group Membership:
<br><input type="radio" name="UserOption" value="1"> Administration
<br><input type="radio" name="UserOption" value="2"> Sales
<p><center><input id="btnOK" type="button" value="Create\Update" name="btnOK"></center>
<br><center><input id="reloadBtn" type="button" value="Reload" name="reloadBtn"></Center>
</b>
<table>
<tr align="right"><td width="20%">Version .03</td></tr>
</table>
</body>
</HTML>
After creating the FSO folder on your c: drive, copy the above code into notepad, edit the necessary changes to address your environment (domain, Exchange server name, and database names) and save it with a .HTA extension.
This should get you off to a good start in making your own application to address your office's needs.
If Exist
Sometimes, we only need to update software on certain systems, as not every system is created equal. For this reason, you can use the if exist line in a batch file.
Here's an example of using the if exist and goto
Let's say that you want to run an install on all machines but you do not want to run the update every time a system logs onto the network, you can add this code to your logon script.
REM ** The REM statement is for comments**
REM ** The first line checks to see if the update.txt file exists, ensuring that the update hasn't already been run.
if exist "c:\update\update.txt" goto End
REM ** If the update.txt file is not present, the following code would be run.
REM ** Map network drive
net use z: \\server\share
REM ** Change to the newly mapped z: drive.
z:
REM ** Change the following to your command that you would run.
installupdate.exe /quiet
REM ** Because we just installed the update, we want to copy the update.txt file to the update folder to
REM ** ensure that the update does not run again on this system.
copy \\server\share\update.txt c:\update\
REM ** No more need for that mapped drive, so let's disconnect it.
net use z: /d
REM ** If the file existed, the update.txt file would have been present and the script would exit.
End:
exit
I hope this example helps you understand the usage and importance of this batch file. We use something similar to this on a regular basis.
Here's an example of using the if exist and goto
Let's say that you want to run an install on all machines but you do not want to run the update every time a system logs onto the network, you can add this code to your logon script.
REM ** The REM statement is for comments**
REM ** The first line checks to see if the update.txt file exists, ensuring that the update hasn't already been run.
if exist "c:\update\update.txt" goto End
REM ** If the update.txt file is not present, the following code would be run.
REM ** Map network drive
net use z: \\server\share
REM ** Change to the newly mapped z: drive.
z:
REM ** Change the following to your command that you would run.
installupdate.exe /quiet
REM ** Because we just installed the update, we want to copy the update.txt file to the update folder to
REM ** ensure that the update does not run again on this system.
copy \\server\share\update.txt c:\update\
REM ** No more need for that mapped drive, so let's disconnect it.
net use z: /d
REM ** If the file existed, the update.txt file would have been present and the script would exit.
End:
exit
I hope this example helps you understand the usage and importance of this batch file. We use something similar to this on a regular basis.
Patching a new system
Microsoft releases many patches. We use System Center Configuration Manager 2007 as our patching system, but sometimes, when we need to get something patched immediately prior to joining a system to the domain or adding it to the network, we need to patch immediately without network access. In order to do so, we usually copy the necessary patches to a folder on the system or onto a CD and place a batch file containing the following code into the same folder.
FOR %%A IN (*.exe) DO %%A /passive /norestart
Copy the code into notepad and save the file with a .bat extension.
This code will run each patch, one-by-one, with the /passive and /norestart command-line switches. You can add a /quiet switch to hide the patches that are installing, but we like to make sure things are running.
Once all of the required patches are installed, we can breath a sigh of relief and add that system to the domain or configure it with the proper network settings.
FOR %%A IN (*.exe) DO %%A /passive /norestart
Copy the code into notepad and save the file with a .bat extension.
This code will run each patch, one-by-one, with the /passive and /norestart command-line switches. You can add a /quiet switch to hide the patches that are installing, but we like to make sure things are running.
Once all of the required patches are installed, we can breath a sigh of relief and add that system to the domain or configure it with the proper network settings.
Subscribe to:
Posts (Atom)