Windows Management and Scripting

A wealth of tutorials Windows Operating Systems SQL Server and Azure

Archive for the ‘VBscript’ Category

Script to search Folder size and owner

Posted by Alin D on August 2, 2011

'******************************************************************
'Returns subdirectories path, size and owner in the given directory which
'are bigger than your specified size and
'******************************************************************
'
'Author: Alin Dumenica,
'Version: 1.01
'Web: http://www.windows-scripting.info
'Revision History:
'Date Author Remark
'--------------+-------+-------------------------------------------------
'Mar 02 2006 PR Initial version
'--------------+--------+-------------------------------------------------
'Usage: cscript search_folder_sizes_and_owner.vbs path_where_to_search where_to_put_result size > logname

‘*********** Declarations and Arguments Handling ***********
Dim ArgObj, path, fname,folsize

Set ArgObj = WScript.Arguments
path = ArgObj(0) ‘ this is the path you want to scan
fname = ArgObj(1) ‘ this is the resulting excel file
folsize = ArgObj(2)
folsize = CInt(folsize)
temp_file1 = path & “~temp1.fol” ‘ temp file that will be deleted at the end
temp_file2 = path & “~temp2.fol” ‘ temp file that will be deleted at the end

searchFolders path, temp_file1, temp_file2, fname, folsize

‘*********** User Functions ***********

Function ShowSubFolders(Folder,fisier,folsize)
For Each Subfolder in Folder.SubFolders
If SubFolder.Attributes AND 2 then
WScript.Echo “This is a system folder: ” & Subfolder.path & “. SKIPPED!”
Else
If Len(SubFolder.Path) > 255 then
Wscript.echo “path is too long”
Else
‘WScript.echo SubFolder.path, SubFolder.Attributes
On Error Resume Next
Folder_Size = SubFolder.Size / (1024*1024)
If Err.number <>0 then
wscript.echo “FOlder: ” & SubFolder.Path & ” was skipped!”
End If
err.clear
Folder_Size = CInt(Folder_Size)
If Folder_Size > folsize Then
fisier.writeline (Subfolder.Path) & “;” & Folder_Size
ShowSubFolders SubFolder, fisier, folsize
End If
End If
End If
Next
End Function

Function searchFolders(Arg1,Arg2, Arg3,Arg4, Arg5)
Dim Folder_Size, res_file
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set filesys = CreateObject(“Scripting.FileSystemObject”)
Set res_file = filesys.CreateTextFile(Arg2, True)
wscript.echo “New file was created: ” & Arg2

ShowSubfolders objFSO.GetFolder(Arg1), res_file, Arg5

wscript.echo “Script has successfully created: ” & Arg2
getowner Arg2, Arg3, Arg4
End Function

Function getowner(temp1,temp2,temp3)
Const ForReading = 1
Set filesys_r = CreateObject(“Scripting.FileSystemObject”)
Set res_file = filesys_r.OpenTextFile(temp1, ForReading)
Set filesys_w = CreateObject(“Scripting.FileSystemObject”)
Set res_file2 = filesys_w.CreateTextFile(temp2, True)

Do While res_file.AtEndOfStream <> True
strCurrentLine = res_file.ReadLine
cut_size_pos = InstrRev(strCurrentLine, “;”,-1,1)
cut_size = left(strCurrentLine,cut_size_pos -1)
ParentFolderPos = InstrRev(cut_size, “”,-1,1)
ParentFolder = left(cut_size, ParentFolderPos)
Set objShell = CreateObject (“Shell.Application”)
Set objFolder = objShell.Namespace (ParentFolder)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)

For Each strFileName in objFolder.Items
if strFileName.Path = cut_size Then
res_file2.writeline objFolder.GetDetailsOf (strFileName, 8)
End If
Next
Loop
wscript.echo “Successfully wroted OWNER!”
res_file.close
res_file2.Close
writetoExcel temp1, temp2, temp3

End Function

Function writetoExcel(fisier1,fisier2, result)

Const ForReading = 1
Set filesys_r1 = CreateObject(“Scripting.FileSystemObject”)
Set res_file = filesys_r1.OpenTextFile(fisier1, ForReading)
Set filesys_r2 = CreateObject(“Scripting.FileSystemObject”)
Set res_file2 = filesys_r2.OpenTextFile(fisier2, ForReading)
Set filesys_w = CreateObject(“Scripting.FileSystemObject”)
Set res_file3 = filesys_w.CreateTextFile(result, True)

Do while res_file.AtEndOfStream <> true
res_file3.writeline res_file.readline & “;” & res_file2.readline
Loop
wscript.echo “Successfully wroted csv file!”
res_file.close
res_file2.Close

End Function

About these ads

Posted in VBscript | Tagged: , | Leave a Comment »

Script to solve client machines not appearing in WSUS Console

Posted by Alin D on June 9, 2011

Depending on your imaging method some clients may not show up on your WSUS console, and refuse to check for updates. Since starting my new job I’ve seen this occur on machines which have been imaged with a non-sysprepped image. I quickly whipped up a script to reset some settings and forcing the machine to contact your WSUS server and retrieve a new Client Id and thus show up in your console.
Dim objShell, strKeyPath, strValueName,strComputer

set objShell = wscript.createObject("wscript.shell")

const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."

Set objWMIService = GetObject("winmgmts:\" & strComputer & "rootcimv2")
Set objRegistry = GetObject("winmgmts:\" & strComputer & "rootdefault:StdRegProv")

strKeyPath = "SOFTWAREMicrosoftWindowsCurrentVersionWindowsUpdate"
strValueName = "SUSClientIdReset"

objRegistry.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, dwValue
IF (dwValue = "1") Then
'do nothing
Else
objRegistry.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,"SusClientId"
objRegistry.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,"SusClientIdValidation"

Set colServiceList = objWMIService.ExecQuery ("Select * from Win32_Service where Name = 'wuauserv'")

For Each objService in colServiceList
If objService.State = "Running" Then
objService.StopService()
Wscript.Sleep 10000
objService.StartService()
End If
Next
objShell.Run("wuauclt /resetauthorization /detectnow ")
Wscript.Sleep 10000
objShell.Run("wuauclt /r /reportnow")

'Set reg value for SUSClientIdReset for checking against later.
dwValue = "1"
objRegistry.SetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, dwValue
End If

Run that on the effected machine with Admin Rights and the client will eventually appear in your WSUS Console.

As for the cause, the master image was joined to the domain and tested. During that time received group policy settings which included WSUS and contacted the server settings it’s clientId.

Posted in VBscript | Tagged: , , | Leave a Comment »

Invetory VBS

Posted by Alin D on August 30, 2010

' Usage: cscript inventory.vbs ComputerName
'Option Explicit
'On Error Resume Next

‘Declare variables

Dim objWbem, objWbemObjectSet, objWbemObject, objWshNetwork, objOS
Dim strScriptPath
Dim strClassName, strPropertyName, strComputerName
Dim CPUType, num, Gb, Iyear, InMonth, IMonth, IDate, months

‘ Check command-line argument collection. If the user supplied an argument,
‘ copy to strComputerName. If the argument contains a question mark,
‘ call the Usage subroutine and exit. If the user didn’t supply an argument, set
‘ strComputerName to the local machine name.

If(WScript.Arguments.Count) Then
strComputerName = WScript.Arguments.Item(0)
If(InStr(strComputerName, “?”)) Then
Call Usage()
End If
Else
Set objWshNetwork = WScript.CreateObject(“WScript.Network”)
strComputerName = objWshNetwork.ComputerName
Set objWshNetwork = Nothing
End If

strScriptPath=Left(wscript.scriptfullname,Len(wscript.scriptfullname)-Len(wscript.scriptname))

ReachResult=reachable(strComputerName)

if ReachResult <> “” then
months =array(“blank”,“Jan”,“Feb”,“Mar”,“Apr”,“May”,“Jun”,“Jul”,“Aug”,“Sep”,“Oct”,“Nov”,“Dec”)
wscript.echo “Computer Name = ” & strComputerName
wscript.echo “IP Address = ” & ReachResult
wscript.echo GetSid(strComputerName)
getInventory strComputerName
GetInstalledAppsReg strComputerName
‘Goto Done
else
wscript.echo strComputerName & “ not reachable”
end if

sub getInventory (StrComputerName)

On Error Resume Next

Set objWbem = GetObject(“winmgmts:\” & strComputerName)

‘  Get the Vendor, Name, ID
strClassName = “Win32_ComputerSystemProduct”
Set objWbemObjectSet = objWbem.ExecQuery(“Select Vendor, Name,IdentifyingNumber From ” & _
strClassName)
strSystemProduct = “”
For Each objWbemObject In objWbemObjectSet
strVendor= “PC Vendor= ” &objWbemObject.Properties_(“Vendor”)
If Err <> 0 Then
strVendor=“PC Vendor = N/A”
Err.Clear
Err.Number = 0
End If

strVenName= “Name= ” & objWbemObject.Properties_(“Name”)
If Err <> 0 Then
strVenName= “Name = N/A”
Err.Clear
Err.Number = 0
End If

strSN= “ID Serial Number= ” & objWbemObject.Properties_(“IdentifyingNumber”)
If Err <> 0 Then
strSN= “ID Serial Number = N/A”
Err.Clear
Err.Number = 0
End If
strSystemProduct=strSystemProduct & strVendor & “ ” & strVenName & “ ” & strSN & “;”
Next

Wscript.Echo strSystemProduct

‘  Get the Family, CurrentClockSpeed, Description
strClassName = “Win32_Processor”
strPropertyName = “Family”
Set objWbemObjectSet = objWbem.ExecQuery(“Select Family,CurrentClockSpeed, Description From ” & _
strClassName)
CPUType = Array(“Other”,“Unknown”,“8086”,“80286”,“80386”,“80486”,“8087”,“80287”,“80387”,“80487”,“Pentium Family”,_
“Pentium Pro”,“Pentium II”,“Pentium MMX”,“Celeron”,“Pentium II Xeon”,“Pentium III”,“M1 Family”,“M2 Family”,_
“K5 Family”,“K6 Family”,“K6-2″,“K6-III”,“Athlon”,“Power PC Family”,“Power PC 601″,“Power PC 603″,“Power PC 603+”,_
“Power PC 604″,“Alpha Family”,“MIPS Family”,“SPARC Family”,“68040”,“68xxx Family”,“68000”,“68010”,“68020”,“68030”,_
“Hobbit Family”,“Weitek”,“PA-RISC Family”,“V30 Family”,“Pentium III Xeon”,“AS400 Family”,“IBM390 Family”,“i860″,_
“i960″,“SH-3″,“SH-4″,“ARM”,“StrongARM”,“6×86″,“MediaGX”,“MII”,“WinChip”)
strProcProfile=“”
For Each objWbemObject In objWbemObjectSet
strProcFamily= “Proc Family = ” & CPUType(objWbemObject.Properties_(“Family”)-1)
If Err <> 0 Then
strProcFamily= “Proc Family = N/A”
Err.Clear
Err.Number = 0
End If

strClock= “Clock Speed = ” & objWbemObject.Properties_(“CurrentClockSpeed”)
If Err <> 0 Then
strClock= “Clock Speed = N/A”
Err.Clear
Err.Number = 0
End If

strDescription= “Description = ” & objWbemObject.Properties_(“Description”)
If Err <> 0 Then
strDescription= “Description = N/A”
Err.Clear
Err.Number = 0
End If
strProcProfile=strProcProfile & strProcFamily & “ ” & strClock & “ ” & strDescription & “;”
Next
WScript.Echo strProcProfile

‘  Get the Memory
strClassName = “Win32_LogicalMemoryConfiguration”
strPropertyName = “TotalPhysicalMemory”
Set objWbemObjectSet = objWbem.ExecQuery(“Select ” & strPropertyName & “ From ” & _
strClassName)
For Each objWbemObject In objWbemObjectSet
strMemory = “Memory = ” & FormatNumber(objWbemObject.Properties_(strPropertyName)/1024,0) & “(Mb)”
If Err <> 0 Then
strMemory= “Memory = N/A”
Err.Clear
Err.Number = 0
End If
WScript.Echo strMemory
Next

‘  Get the Release Date
strClassName = “Win32_BIOS”
strPropertyName = “ReleaseDate”
Set objWbemObjectSet = objWbem.ExecQuery(“Select ” & strPropertyName & “ From ” & _
strClassName)
For Each objWbemObject In objWbemObjectSet
Iyear = left(objWbemObject.Properties_(strPropertyName),4)
InMonth = mid(objWbemObject.Properties_(strPropertyName),5,2)
IDate = mid(objWbemObject.Properties_(strPropertyName),7,2)
months = array(“blank”,“Jan”,“Feb”,“Mar”,“Apr”,“May”,“Jun”,“Jul”,“Aug”,“Sep”,“Oct”,“Nov”,“Dec”)
strBios = “Date BIOS Released = ” & IDate & “ ” & Months(InMonth) & “ ” & Iyear
WScript.Echo strBios
Next

‘  Get the Install Date
strClassName = “Win32_OperatingSystem”
strPropertyName = “InstallDate”
Set objWbemObjectSet = objWbem.ExecQuery(“Select ” & strPropertyName & “ From ” & _
strClassName)
For Each objWbemObject In objWbemObjectSet
Iyear =left(objWbemObject.Properties_(strPropertyName),4)
InMonth = mid(objWbemObject.Properties_(strPropertyName),5,2)
IDate = mid(objWbemObject.Properties_(strPropertyName),7,2)
strOSInst = “Date OS installed = ” & IDate & “ ” & Months(InMonth) & “ ” & Iyear
WScript.Echo strOSInst
Next
For Each objOS in GetObject(“winmgmts:\” & strComputerName).InstancesOf (“Win32_OperatingSystem”)
strOSName= “Name = ” & objOS.Caption & “, Version = ” & objOS.Version
If Err <> 0 Then
strOSName= “Name = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strOSName

strSysDesc= “System Description = ” & objOS.Description
If Err <> 0 Then
strSysDesc= “System Description = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strSysDesc

strRegUser= “Registered User = ” & objOS.RegisteredUser
If Err <> 0 Then
strRegUser=“Registered User = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strRegUser

strOrg= “Organization = ” & objOS.Organization
If Err <> 0 Then
strOrg= “Organization = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strOrg

strLicUser= “Number of Licensed Users = ” & objOs.NUmberOfLicensedUsers
If Err <> 0 Then
strLicUser= “Number of Licensed Users = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strLicUser

strNumUsers= “Number of Users = ” & objOS.NumberOfUsers
If Err <> 0 Then
strNumUsers= “Numer of Users = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strNumUsers

strOSSN= “Serial Number = ” & objOS.SerialNumber
If Err <> 0 Then
strOSSN= “Serial Number = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strOSSN

strBuild= “Build Type = ” & objOS.BuildType
If Err <> 0 Then
strBuild= “Build Type = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strBuild

strSP= “Service Pack = ” & objOS.ServicePackMajorVersion & “.” & objOS.ServicePackMinorVersion
If Err <> 0 Then
strSP= “Service Pack = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strSP

strInstType= “Product Installation Type = ” & objOS.OSProductSuite
If Err <> 0 Then
strInstType= “Product Installation Type = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strInstType

strEncr= “System Encryption Level = ” & objOS.EncryptionLevel
If Err <> 0 Then
strEncr= “System Encryption Level = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strEncr

strPhysMem= “Physical Memory = ” & FormatNumber((objOS.TotalVisibleMemorySize /1024),2) & “ MBytes”
If Err <> 0 Then
strPhysMem= “Physical Memory = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strPhysMem

strFreeMem= “Free Physical Memory = ” & FormatNumber((objOS.FreePhysicalMemory /1024),2) & “ MBytes”
If Err <> 0 Then
strFreeMem= “Free Physical Memory = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strFreeMem

strStatus= “System Status = ” & objOS.Status
If Err <> 0 Then
strStatus= “System Status = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strStatus

strBoost= “Foreground Application Boost = ” & objOS.ForegroundApplicationBoost
If Err <> 0 Then
strBoost= “Foreground Application Boost = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strBoost

strBootDrv= “Boot Device = ” & objOS.BootDevice
If Err <> 0 Then
strBootDrv= “Boot Device = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strBootDrv

strSysDir= “System Directory = ” & objOS.SystemDirectory
If Err <> 0 Then
strSysDir= “System Directory = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strSysDir

strLastBoot= “Last Boot Time = ” & objOS.LastBootUpTime
If Err <> 0 Then
strLastBoot= “Last Boot Time = N/A”
Err.Clear
Err.Number = 0
End If
Wscript.Echo strLastBoot

Next

‘  Get the DiskDrive
strClassName = “Win32_DiskDrive”
strPropertyName = “Size”
Set objWbemObjectSet = objWbem.ExecQuery(“Select ” & strPropertyName & “ From ” & _
strClassName)
For Each objWbemObject In objWbemObjectSet
Gb = FormatNumber(objWbemObject.Properties_(strPropertyName) / (1024^3),1)
If Not IsNull(Gb) Then
strDiskSize= “Disk Size = ” & Gb & “ Gb”
Else
strDiskSize= “Disk Size = N/A”
End If
If Err <> 0 Then
strDiskSize= “Disk Size = N/A”
Err.Clear
Err.Number = 0
End If
WScript.Echo strDiskSize
Next

‘  Get the Username
strClassName = “Win32_ComputerSystem”
strPropertyName = “UserName”
Set objWbemObjectSet = objWbem.ExecQuery(“Select ” & strPropertyName & “ From ” & _
strClassName)
For Each objWbemObject In objWbemObjectSet
strLastUser=“User Last = ” & objWbemObject.Properties_(strPropertyName)
If Err <> 0 Then
strLastUser= “User Last = N/A”
Err.Clear
Err.Number = 0
End If
WScript.Echo strLastUser
Next

‘wscript.echo vbCrLf & ucase(strComputerName) & ” Software:”
‘  Get the Software
‘   strClassName = ”Win32_Product”
‘   strPropertyName = ”Caption”
‘   Set objWbemObjectSet = objWbem.ExecQuery(“Select Name, InstallDate, Version, Vendor From ” & _
‘       strClassName)
‘   For Each objWbemObject In objWbemObjectSet
‘           WScript.Echo objWbemObject.Properties_(“Name”)
‘           WScript.Echo ”Version = ” & objWbemObject.Properties_(“Version”)
‘           WScript.Echo ”Vendor = ” & objWbemObject.Properties_(“Vendor”)
‘       Iyear = left(objWbemObject.Properties_(“InstallDate”),4)
‘       InMonth = mid(objWbemObject.Properties_(“InstallDate”),5,2)
‘       IDate = mid(objWbemObject.Properties_(“InstallDate”),7,2)
‘           WScript.Echo ”InstDate = ” & IDate & ” ” & Months(InMonth) & ” ” & Iyear & vbCrLf
‘   Next

end sub

Set objWbem = Nothing
WScript.Quit(1)

‘ Usage Subroutine
Sub Usage()
WScript.Echo “Usage:” & vbNewLine &_
“C:> wscript | cscript  wbem.vbs  [Hostname]“ & vbNewLine &_
“Hostname: Optional target host. Local host if omitted.”
WScript.Quit(0)
End Sub

Function reachable(HostName)

Dim wshShell, fso, tfolder, tname, TempFile, results, retString, ts
Const ForReading = 1, TemporaryFolder = 2
reachable = False
Set wshShell = CreateObject(“wscript.shell”)
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
TempFile =fso.buildpath(tfolder, tname)
‘-w 100000 is 5 mins worth of timeout
wshShell.Run “cmd /c ping -n 2 -w 500 ” & HostName & “>” & TempFile, 0, True
Set results = fso.GetFile(TempFile)
Set ts = results.OpenAsTextStream(ForReading)
Do While ts.AtEndOfStream <> True
retString = ts.ReadLine
If InStr(retString, “Reply”) > 0 Then
retString = GetIPAddress(retString)
reachable = retString
‘wscript.echo retString
‘wscript.echo retString & vbTab, LogCompAccts
Exit Do
End If
Loop
If InStr(1, retString, “.”) Then
reachable = retString ‘Left(retString,Len(RetString))
Else
reachable = “”
End If

ts.Close
results.Delete
End Function

Function GetIPAddress(strIPResponse)

strColon = InStr(1, strIPResponse, “:”)
strRealAddress = Left(strIPResponse, strColon1)
strStart = InStrRev(strRealAddress, “m”)
strEnd = Len(strRealAddress) - (strStart + 1)
GetIPAddress = Right(strRealAddress, strEnd + 1)
GetIPAddress=Trim(CStr(GetIPAddress))

End Function

Function GetSID(HostName)

Dim wshShell, fso, tfolder, tname, TempFile, results, retString, ts
Const ForReading = 1, TemporaryFolder = 2

Set wshShell = CreateObject(“wscript.shell”)
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
TempFile =fso.buildpath(tfolder, tname)
strCommand=fso.BuildPath(strScriptPath, “psgetsid.exe”)
GetSID =“SID = N/A”

strBlast=“cmd /c ” & Chr(34) & strCommand & Chr(34) & “ \” & HostName & “ >” &  TempFile

wshShell.Run strBlast , 0, True

Set results = fso.GetFile(TempFile)
Set ts = results.OpenAsTextStream(ForReading)
Do While ts.AtEndOfStream <> True
retString = ts.ReadLine
If InStr(retString, “S-“) > 0 Then
GetSID=“SID = ” & Right(retString,Len(retString)-1)
‘retString = GetSIDAddress(retString)
Exit Do
End If
Loop

ts.Close
results.Delete

End Function

Sub GetInstalledAppsReg(HostName)

Dim oRegistry, sBaseKey, iRC, sKey, arSubKeys, sValue

Const HKLM = &H80000002 ‘HKEY_LOCAL_MACHINE

Set oRegistry = GetObject(“winmgmts:\” & HostName & “/root/default:StdRegProv”)

sBaseKey = “SOFTWAREMicrosoftWindowsCurrentVersionUninstall”

iRC = oRegistry.EnumKey(HKLM, sBaseKey, arSubKeys)

‘wscript.echo ”Software: ”
For Each sKey In arSubKeys
iRC = oRegistry.GetStringValue(HKLM, sBaseKey & sKey, “DisplayName”, sValue)

If iRC <> 0 Then
oRegistry.GetStringValue HKLM, sBaseKey & sKey, “QuietDisplayName”, sValue
End If

If sValue <> “” Then
wscript.echo sValue
ElseIf Err <> 0 Then
wscript.echo “Installed App Name N/A”
err.clear
err.Number=0
End If
Next

End Sub

‘In addition you can also use the Windows Installer object
‘indirectly with WMI (the Win32_Product Class) to get a list
‘of software that is installed with MSI, but this list will
‘most likely only be a subset of the Uninstall listing anyway,
‘so it ’s really no point.

‘Here is a WMI script that lists all software installed by MSI:

Sub GetInstalledAppsMSI(HostName)

Dim strClassName, strPropertyName, objWbem, objWbemObjectSet, objWbemObject

strClassName = “Win32_Product”
strPropertyName = “Caption”

Set objWbem = GetObject(“winmgmts:\” & HostName)
Set objWbemObjectSet = objWbem.ExecQuery(“Select Name, Version From ” & strClassName)

For Each objWbemObject In objWbemObjectSet
Debug.Print HostName & “ ” & objWbemObject.Properties_(“Name”)
Debug.Print HostName & “ ” & “  Version: ” & objWbemObject.Properties_(“Version”)
Next

End Sub

Posted in Scripting, VBscript | Tagged: , , , | Leave a Comment »

Deploy MSI package to a list of Computers

Posted by Alin D on August 10, 2010

This script will deploy an MSI package to a group of workstations (provided in a text file). All you need is the list of workstations, the software package, and Microsoft Excel (and again, administrative access to each workstation from the command line).
' File Name: deployMSI.VBS
' Script Name: deployMSI.VBS
' ------------------------------------------------------------------------------
' ARGUMENTS :
' None
' ------------------------------------------------------------------------------

' ------------------------------------------------------------------------------
' PURPOSE :
' PURPOSE :
' Installs an MSI on a remote workstation from a network share and logs the
' result to an Excel spreadsheet.
' - The script will copy the source folder to the target machine and invoke the
' Windows Installer to install the application using any preconfigured
' switches to control the installation.
' - The script will then follow up and parse through the application log and
' check the result of the installation, reporting it in an Excel spreadsheet.
' * NOTE: Excel must be installed on the workstation the script is run from.
' ------------------------------------------------------------------------------
'
' ------------------------------------------------------------------------------
' REVISION HISTORY :
' Date:
' Time:
' Issue:
' Solution:
' ------------------------------------------------------------------------------

Option Explicit

' ------------------------------------------------------------------------------
' FUNCTION LISTINGS
' ------------------------------------------------------------------------------
' Function: getInstallStatus
' Created: 2007.12.26
' Author: Sunit Tuladhar
' Arguments: strSuccess & strFailed, defined in verifyInstall subroutine.
' ------------------------------------------------------------------------------
' Purpose:
' Checks the installation status in the remote workstation Application log.
' ------------------------------------------------------------------------------
Function getInstallStatus(strSuccess, strFailed, strComputer)
Dim intCount, intFailed

intCount = getEventLogCount(strSuccess, strComputer)

If intCount > 0 Then
getInstallStatus = "P"
Else
intFailed = getEventLogCount(strFailed, strComputer)
If intFailed > 0 Then
getInstallStatus = "F"
Else
getInstallStatus = "U"
End If
End If
End Function

' ------------------------------------------------------------------------------
' Function: getEventLogCount
' Created: 2007.12.26
' Author: Sunit Tuladhar
' Arguments: strWQL, success or failure WQL defined in verifyInstall subroutine.
' ------------------------------------------------------------------------------
' Purpose:
' Counts the number of events in an event log matching specific criteria
' defined via WQL query (see subVerifyInstall).
' ------------------------------------------------------------------------------
Function getEventLogCount(strWQL, strComputer)
Dim colLoggedEvents
Dim objWMISvc

Set objWMISvc = GetObject("winmgmts:" & "{(Security)}\" & strComputer & _
"rootcimv2")
Set colLoggedEvents = objWMISvc.ExecQuery(strWQL)

getEventLogCount = colLoggedEvents.Count
End Function

' ------------------------------------------------------------------------------
' Function: getEventLogMsg
' Created: 2007.12.26
' Author: Sunit Tuladhar
' Arguments: strWQL, success or failure WQL defined in verifyInstall subroutine.
' ------------------------------------------------------------------------------
' Purpose:
' Collects the event log descriptions for each event log entry collected
' according to the WQL query in Function getEventLogCount.
' ------------------------------------------------------------------------------
Function getEventLogMsg(strWQL, strComputer)
Dim colLoggedEvents
Dim objEvent, objWMISvc
Dim strMsg

Set objWMISvc = GetObject("winmgmts:" & "{(Security)}\" & strComputer & _
"rootcimv2")
Set colLoggedEvents = objWMISvc.ExecQuery(strWQL)

For Each objEvent In colLoggedEvents
strMsg = strMsg & chr(13) & objEvent.Message
Next

' This is the length of the event log description to capture.
' *** CHANGE TO SUIT NEEDS AS NECESSARY ***
getEventLogMsg = Left(strMsg, 255)
End Function

' ==============================================================================
' SCRIPT BODY
' ==============================================================================
Dim a, b, DD, MM, YYYY, vDy, vMo
Dim errReturn, FileName, intProcessID
Dim objExcel, objExecObject, objFSO, objShell, objSheet, objTxtFile, objWMISvc
Dim strComputer, strDestPath, strExcelFile, strExcelPath, strInstaller, strList
Dim strPing, strSourcePath, strText, strWkstn

Const ForReading = 1

' Bind to the file system object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Bind to the shell object
Set objShell = CreateObject("WScript.Shell")

' Execute the subroutines in the correct order (since they're listed by alpha).
subGetDate
subCreateExcelWorkbook
subMain
' Pause the script for two minutes to allow the installations to complete
' (unnecessary if deploying to a large number of workstations)
WScript.Echo "Pausing script for 2 minutes and 30 seconds at " & Now
WScript.Sleep 120000
subVerifyInstall
subCleanUp

Sub subCleanUp
WScript.Echo "Beginning clean up..."

' Save the spreadsheet and close the workbook
objExcel.ActiveWorkbook.SaveAs strExcelFile
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit

WScript.Echo "Clean up and script complete."
End Sub

Sub subCreateExcelWorkbook
' Define the filename for the Excel file
strExcelFile = YYYY & vMo & vDy & "deployMSI.XLSX"

' Bind to the Excel application object
Set objExcel = CreateObject("Excel.Application")

' If Excel not found, exit script
If (Err.Number 0) Then
WScript.Echo "Excel application not found."
WScript.Quit
End If

' Create a new workbook
objExcel.Workbooks.Add

' Bind to and name the first worksheet in the workbook
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
' *** CHANGE TO SUIT NEEDS AS NECESSARY ***
objSheet.Name = "Some Program Deployment"

' Populate spreadsheet cells (column headings) with user-defined attributes
' *** CHANGE TO SUIT NEEDS AS NECESSARY ***
objSheet.Cells(1, 1).Value = "Target Computer"
objSheet.Cells(1, 2).Value = "Time"
objSheet.Cells(1, 3).Value = "Ping"
objSheet.Cells(1, 4).Value = "MsiInstaller Result"
objSheet.Cells(1, 5).Value = "Installation Result"
End Sub

' This subroutine gets the year, month and day for the purposes of building the
' Excel filename in the subroutine subCreateExcelWorkbook
Sub subGetDate
YYYY = Year(Now)
MM = Month(Now)
DD = Day(Now)

If MM < 10 Then
vMo = "0" & MM
Else
vMo = MM
End If

If DD 0 Then
WScript.Echo "Starting on " & strWkstn & "..."

' Time stamp the spreadsheet
objSheet.Cells(a, 2).Value = Now

' Copy the installer package to the target PC
objFSO.CopyFolder strSourcePath, strDestPath, True

' Start the installer
Set objWMISvc = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\" & strWkstn & _
"rootcimv2:Win32_Process")

' Variable holding the error return code from the MSI installer
errReturn = objWMISvc.Create(strInstaller, Null, Null, _
intProcessID)

If errReturn = 0 Then
objSheet.Cells(a, 1).Value = strWkstn
objSheet.Cells(a, 4).Value = "Started"
Else
objSheet.Cells(a, 1).Value = strWkstn
objSheet.Cells(a, 4).Value = "Failed"
End If
Else
WScript.Echo vbTab & strWkstn & " unreachable on network."
objSheet.Cells(a, 1).Value = strWkstn
objSheet.Cells(a, 2).Value = Now
objSheet.Cells(a, 3).Value = "Unreachable on network."
objSheet.Cells(a, 4).Value = "Failure"
End If
Loop

' Increment the Excel row variable to move to the next row down
a = a + 1
Loop

' Close the text file
objTxtFile.Close
WScript.Echo "Deployment complete."
End Sub

Sub subVerifyInstall
WScript.Echo "Verifying execution..."

Dim intEvtCode
Dim objFolder
Dim strEvtMsg, strFailed, strStatus, strSource, strSuccess

' Define the Source being looked for in the Application log
' *** CHANGE TO SUIT NEEDS AS NECESSARY ***
strSource = "MsiInstaller"

' Define the Event IDs being looked for in the Application log
' *** CHANGE TO SUIT NEEDS AS NECESSARY ***
intEvtCode = 11707

' WQL query definition to look for any entries in the application log from a
' specific source with a specific event code
strFailed = "Select * From Win32_NTLogEvent Where Logfile = 'Application'" _
& " and SourceName = '" & strSource & "' and Type = 'Error'"
strSuccess = "Select * From Win32_NTLogEvent Where Logfile = 'Application'" _
& " and SourceName = '" & strSource & "' and EventCode = " & intEvtCode

' Set the Excel row variable to start on the second row
b = 2
Do While objSheet.Cells(b, 1).Value ""
strComputer = objSheet.Cells(b, 1).Value

' Ping the workstation, skipping it if it is unreachable on the network
strPing = "%comspec% /c ping -n 3 -w 1000 " & strComputer & ""
Set objExecObject = objShell.Exec(strPing)

Do While Not objExecObject.StdOut.AtEndOfStream
strText = objExecObject.StdOut.ReadAll()

If InStr(strText, "Reply") > 0 Then
' Parse the application log based upon the value of the cell in the
' fourth column of the spreadsheet
Select Case objSheet.Cells(b, 4).Value
Case "Started"
WScript.Echo "Verifying execution on " & strComputer & "..."

On Error Resume Next
strStatus = getInstallStatus _
(strSuccess, strFailed, strComputer)

If strStatus = "F" Then
strEvtMsg = getEventLogMsg(strFailed, strComputer)
Else
strEvtMsg = getEventLogMsg(strSuccess, strComputer)
End If
objSheet.Cells(b, 5).Value = strEvtMsg
On Error GoTo 0

' Delete the folder copied to the workstation from the share
Set objFolder = objFSO.GetFolder("\" & strComputer & _
"C$destPath")
If objFSO.FolderExists(objFolder) Then
objFolder.Delete True
WScript.Echo "Install folder deleted."
End If
Case Else
End Select
Else
WScript.Echo vbTab & strComputer & " unreachable on network."
End If
Loop

b = b + 1
Loop

WScript.Echo "Verification complete."
End Sub
' ==============================================================================
' END OF SCRIPT: deployMSI.VBS
' ==============================================================================

Posted in Scripting, VBscript | Leave a Comment »

Prevent logoff

Posted by Alin D on August 10, 2010

This script is designed to prevent a logoff from happening if a specific program is running, otherwise, if the program isn’t found, let the logoff process continue. I don’t know everyone’s script knowledge level so just in case I need to clarify I use the words process/program/executible interchangeably throughout the following explanation:

When the script is double-clicked it searches through the process list for an executible file. In the example below the executible is called vmware-vmx.exe. If this process is running on the computer the script will display a message to the user stating “x VMs are running. Please turn them off before continuing to logoff”. If the process is not found the script will logoff the user. In order for this to work you need to put a shortcut to this script in the Start menu (and/or desktop) and edit local group policy so that the logoff button no longer appears in the Start or Ctrl+Alt+Del menu. This will force users to click on the script whenever they want to logoff. You also need to change the process/program name to whatever program you want the script to search for. Replace where it says vmware-vmx and VMware with your program’s name. You can also use this script to prevent shutdown and restart. I made a comment towards the end of the script as to how.
'************************************************************
' PREVENT LOGOFF SCRIPT
' Created: 6/14/2007
' Updated: 7/3/2007
'
' A big THANK YOU to Adam, Jaker, Guy Thomas, and Lisa
' ***********************************************************

‘ Require all variables to be declared before they can be used.
‘ This helps with debugging issues
Option Explicit

‘ Define all of the variables
Dim strComputer, objWMIService, colProcesses,
Dim objProcess, strList, VMcount

‘ Establish variables
strComputer = “.” ‘setting strComputer to “.” connects to the local machine.
VMcount = 0 ‘starts the process count at 0

‘ All WMI scripts begin by connecting to the Windows Management Instruments interface
Set objWMIService = GetObject(“winmgmts:” _
& “{impersonationLevel=impersonate}!\” _
& strComputer & “rootcimv2″)

‘ Get a collection of all running processes
Set colProcesses = objWMIService.ExecQuery(“Select * FROM Win32_Process”)

‘ Cycle through every currently running process
For Each objProcess in colProcesses
‘Check to see if the program is currently running
If objProcess.Name = “vmware-vmx.exe” Then
‘the program is running if the above statement is true.
VMcount = VMcount + 1 ‘Count the number of running processes
End If
Next
If VMcount > 0 Then
‘Build the message box text notifying the user of any running processes
strList = strList & VMcount _
& ” VMware process(es) running.” _
& ” Please power off before continuing to logoff.” & vbCr
‘This message box will only appear if the process was found
WSCript.Echo strList
Else
‘Create another variable to connect to the Windows shell service.
Dim objWSHShell
‘Connect to the Windows shell service
Set objWSHShell = CreateObject(“WScript.Shell”)
‘Execute the logoff command to logoff
objWSHShell.Run “shutdown -l” ‘change to -s to shutdown or -r to restart
End if
‘Quit the script
WScript.Quit

Posted in Scripting, VBscript | Leave a Comment »

Delete Old SQL backups

Posted by Alin D on August 5, 2010

Dim DateLimit
Dim fso, flder, fs, f, backFolder
backFolder = "W:SQLBackupsSQLLiteSpeedFullBackup"
set fso = createObject("Scripting.FileSystemObject")
set flder = fso.getfolder(backFolder)
set fs = flder.files
for each f in fs
if f.DateLastModified < DateAdd("d", -1, date) then
f.delete
end if
next
backFolder = "W:SQLBackupsSQLLiteSpeedDifferentialBackup"
for each f in fs
if f.DateLastModified < DateAdd("d", -1, date) then
f.delete
end if
next
backFolder = "W:SQLBackupsSQLLiteSpeedTransactionalLogBackup"
for each f in fs
if f.DateLastModified < DateAdd("h", -40, date) then
f.delete
end if
next
Set fs = nothing
Set flder = Nothing
Set fso = Nothing
Set fs = Nothing
Set f = Nothing
Set backFolder = Nothing

Posted in Scripting, VBscript | Leave a Comment »

Another way to use Shell, FileSystemObject and other objects in WSH/vbcript

Posted by Alin D on July 27, 2010

When automating tasks with Windows Script Host in most of the time we must use objects such as WScript.Shell, WScript.Network, Scripting.FileSystemObject and others because they allow us to implement the actions that we need at the moment. The problems begin because many do not remember the syntax for creating each of these objects and thus we have to refer to the help or VBS code already developed. To facilitate the use of common objects such as Shell, FileSystemObject, Network and wmi we created the ObjectManager  Class which makes available these objects without having to believe that one of them, since the class is does for us. To use only we must include and is ready to operate.

1.Include "ObjectManager.class"

After this instruction in our VBS code automatically have available an object named ObjectManager with which we can make use of the objects mentioned above through the following properties:

  • Shell: Return a reference to an object of type “WScript.Shell”.
  • Net: Return a reference to an object of type “WScript.Network”.
  • Fso: Return a reference to an object of type “Scripting.FileSystemObject”.
  • Wmi: Return a reference to an object of type “winmgmts:” in local computer.

Let us now see some examples of its use:

01.'Calling to WScript.Network Property
02.WScript.Echo ObjectManager.Net.ComputerName
03.'Calling to Scripting.FileSystemObject Method.
04.WScript.Echo ObjectManager.Fso.GetFile("ObjectManager.class").Path
05.'Calling to WScript.Shell Property
06.WScript.Echo ObjectManager.Shell.CurrentDirectory
07.'Calling to WMI (Windows Management Instrumentation) Method
08.Dim So
09.For Each So in ObjectManager.Wmi.ExecQuery("Select * from Win32_OperatingSystem")
10. WScript.Echo "Operating System: " & So.Caption
11. WScript.Echo "Version: " & So.Version
12. WScript.Echo "Service Pack: " & So.CSDVersion
13.Next

The Property wmi works by default with the namespace “rootcimv2″ but through the method SetWmiNameSpace we can change it, let’s see an example:

1.'Changing WMI (Windows Management Instrumentation) NameSpace to "StdRegProv"
2.ObjectManager.SetWmiNameSpace("rootdefault:StdRegProv")
3.const HKEY_LOCAL_MACHINE = &H80000002
4.Dim arrSubKeys,strSubKey
5.ObjectManager.Wmi.EnumKey HKEY_LOCAL_MACHINE, "SYSTEMCurrentControlSetServices", arrSubKeys
6.For Each strsubkey In arrSubKeys
7. wscript.Echo strSubkey
8.Next

Posted in Scripting, VBscript | Tagged: , , , | Leave a Comment »

VBScript to backup SQL 2000

Posted by Alin D on July 24, 2010

‘Script BackupSQL.VBS
‘Script Created By Suparatul
‘April 2008

Dim oServer

Dim oDatabase

Dim oBackup

Dim sBAKFilePath

‘change this to where ever you want to place your backup files, no trailing

‘backslash, we add it below

sBAKFilePath = “D:SQLBACKUP”

‘we need a backup object in addition to the sqlserver one

Set oServer = CreateObject(“SQLDmo.SqlServer”)

Set oBackup = CreateObject(“SQLDmo.Backup”)

oServer.LoginSecure = True

oServer.Connect “(local)”

‘this will do a full backup of every database except TempDB to a file (not a

‘device

For Each oDatabase In oServer.Databases

If UCase(oDatabase.Name) “TEMPDB” Then

oBackup.Database = oDatabase.Name

‘remove any previous backup – same as using T-SQL with init

oBackup.Initialize = True

‘dynamically create the name of the backup file

oBackup.Files = sBAKFilePath & “” & oDatabase.Name & “.bak”

‘set the action property as needed

‘0 = Full backup

‘1 = Differential

‘2 = Specified files only

‘3 = Log backup

oBackup.Action = 0

oBackup.SQLBackup oServer

End If

Next

‘clean up

Set oBackup = Nothing

oServer.DisConnect

Set oServer = Nothing

Posted in Scripting, VBscript | Tagged: , | Leave a Comment »

VBScript Tutorial for Creating a User Account

Posted by Alin D on July 24, 2010

This page has VBScript examples, which show you how to create User accounts in your Windows Server 2003 domain. I urge you to trust me, and build your scripts in stages. The benefit of creating scripts in small sections is that not only do you understand each part, but also your brain will see ways of applying a section in a different scenario. For example, once you learn how to bind with Active Directory to create a User object, it’s easy to modify the script and create a Computer object instead.
Example 1 – Script to Create a User in Active Directory

On this page we concentrate on the essential VBscript commands necessary to build a User account in Active Directory Users and Computers. For example, GetObject(“LDAP://rootDSE”) and .Create(“User”). Even though I am experienced at creating VBScripts, I still run manually through creating the object in Active Directory Users and Computers, the menus actions help me to rehearse the stages in my scripts.
Prerequisites

I recommend that you logon at a Windows Server 2003 domain controller. If you are a long way from the server, Remote Desktop would be a suitable alternative. If that is not possible, you could get these scripts to work from an XP machine as a non-administrator. However, why introduce extra complications? Especially at the beginning, you want easy success, with fewest obstacles.

Instructions for Creating a User Account in Active Directory

1. You should run this VBScript on a Windows Active Directory domain.
2. Copy and paste the example script below into notepad or a VBScript editor.
3. Decide whether to change the value for strUser. DomGuy2 is not a particularly attractive name.
4. Save the file with a .vbs extension, for example: Users .vbs.
5. Double click Users .vbs and check the Users container for strUser.

Script to Create a User in a Named OU (Organizational Unit)

‘ Users .vbs
‘ Sample VBScript to create a User in Users .
‘ Author Guy Thomas http://Computerperformance.co.uk/
‘ Version 1.3 – September 2005
‘ ——————————————————‘
Option Explicit
Dim strUser
Dim objRootLDAP, objContainer, objNewUser
strUser = “DomGuy2″

‘ Bind to Active Directory, Users container.
Set objRootLDAP = GetObject(“LDAP://rootDSE”)
Set objContainer = GetObject(“LDAP://cn=Users,” & _
objRootLDAP.Get(“defaultNamingContext”))

‘ Build the actual User.
Set objNewUser = objContainer.Create(“User”, “cn=” & strUser)
objNewUser.Put “sAMAccountName”, strUser
objNewUser.SetInfo

WScript.Quit

‘ End of free sample Create Users VBScript.

VBScript Tutorial – Learning Points

Note 1: The first 10 lines explain the purpose of the script and declare the variables.

Note 2: The simple, but clever command, which allows the script to work with any domain is: GetObject(“LDAP://rootDSE”). Crucial, this statement binds WSH / VBScript to Active directory. The next line puts the focus on the Users container, as that is where the user will be born. Incidentally, the correct syntax is cn=users, whereas OUs that you create need the OU= prefix, for example OU=Accounts,.

Note 3: sAMAccountName controls the logon name, this is the name that users should enter in the dialog box after they press the Ctrl Alt Delete, logon sequence.

Note 4: .Create is a method to build an object. See how we use “User” not “Computer” or “OU”.

Note 5: When creating or modifying users, invariably you need .put and .SetInfo. The .put method is the equivalent of selecting a box in Active Directory Uses and Computers, in this example sAMAccountName sets the correct property and .put unloads the value set by strUser. .SetInfo is the VBScript equivalent of pressing the OK button in the GUI. In both cases it represents the final act of creating or modifying the User object.

Note 6: This script represents ‘work in progress’. For a real production script you would need to enable the account, and most likely, add several other properties, for example givenName. My desire is to get you started. Build the script in stages, understand each component, then add another section.
Guy Recommends: WMI Monitor and Its Free!
Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems. Fortunately, Solarwinds have created the WMI Monitor so that you can examine these gems of performance information for free. Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor
Example 2: Script to Create a User in a Named OU (Organizational Unit)

Prerequisites

Create a new OU. I called my OU Accounts, what name will your choose?

Instructions for Creating a User Account in a Named OU

1. Copy and paste the example script below into notepad or a VBScript editor.
2. Find the strContainer, and then change to the name of your OU.
3. Decide whether to change the value for strUser.
4. Save the file with a .vbs extension, for example: ComputerOU.vbs.
5. Double click ComputerOU.vbs and check the Computers container for strComputer.

‘ UserOU.vbs
‘ Sample VBScript to create a User in a named OU.
‘ Author Guy Thomas http://Userperformance.co.uk/
‘ Version 2.4 – September 2005
‘ ——————————————————‘
Option Explicit
Dim objRootLDAP, objContainer, objUser, objShell
Dim strUser, strName, strContainer

strUser = “BookKeeper21″
strName = “Bookie”
strContainer = “OU=Accounts ,” ‘ Note the comma

‘ Bind to Active Directory, Users container.
Set objRootLDAP = GetObject(“LDAP://rootDSE”)
Set objContainer = GetObject(“LDAP://” & strContainer & _
objRootLDAP.Get(“defaultNamingContext”))

‘ Build the actual User.
Set objUser = objContainer.Create(“User”, “cn=” & strUser)
objUser.Put “sAMAccountName”, strUser
objUser.Put “givenName”, strName
objUser.SetInfo

‘ Optional section to launch Active Directory Uses and Users
Set objShell=CreateObject(“WScript.Shell”)
objShell.Run “%systemroot%system32dsa.msc”

WScript.Quit

‘ End of Sample UserOU VBScript.

VBScript Tutorial – Learning Points

Note 1: The key difference between the two scripts is: strContainer = “OU=Accounts ,”. Trace how VBScript applies this variable to set the Organizational Unit.

Note 2: This command looks easy to script: GetObject(“LDAP://” & strContainer & _. However it took me ages to get the speech marks and ampersands (&) just right.

Note 3: objShell.run. This optional section is just me having a little fun. What this section does is open the Active Directory Users and Users MMC ready for you to inspect the new User account. My other reason for adding this code is show that the script has executed successfully, otherwise I just sit and wonder if it has finished yet.

Note 4: I suggested in Example 1 that you could add other attributes, trace how I added givenName through strName. To see what I mean, I suggest that you alter the value from “Bookie” to a more realistic name.
Summary of Creating User Accounts

The first example script shows you how to create a new user account in your Windows Server 2003 domain. In the second example we control the name of the OU where the account appears in Active Directory Users and Computers. The tutorial’s hidden agenda is learning how to apply the VBScript object, methods and value technique. There is one other guiding principle, start simply. Build complex scripts in stages.

Posted in Scripting, VBscript | Tagged: , , , , , , | Leave a Comment »

Standards to creating a Vbscript Classes Repository

Posted by Alin D on July 23, 2010

Considering that we already have available a method to perform includes in vbscript as we explained in our article on Using Includes in vbscript it is easy to imagine a scenario where all of our classes or scripts are stored in one place and that through an instruction or command include can load and use. In short to have a Vbscript Classes Repository with the benefits of code reuse and we can use in a logical and organized manner. To achieve this goal we must generate a series of conventions that provide instructions or pattern and define their use, and which we propose the following:

* Every new script vbscript is created from the template IncludeTemplate.vbs (See article here) to get:
o Ability to include code in your scripts through the Include clause.
o The collection IncludeFilesList used by the template avoids the inclusion of more than once a file or class code, this allows you to run recursive include without any problem because the code will be included only once.
o The variable RepositoryFolderPath sets the standard directory path where we have to store all of our code files and classes. With this definition we only need to reference the files by name only because the subroutine Include will search first in the directory path.
* Is defined as a principle that every code file or class definition must be stored in the directory path defined for the classes repository.
* Any code that we think can be recycled, should be defined as a class with their properties and methods.
* The name of the file containing the definition of a class must equal the name of the class adding the extension .class this allows to easily find file include knowing the name of the class that we use in our script, that is: File Name = Class Name + .class.
* In the definition of a class can do Include in the header to other classes follow the same structure as explained above, this is valid because there is only one routine Include and is written in the original script and it controls to be including. In a few words in the definition of a classes there will be no routine Include and every time you make an include will be used routine Include in our script.

Finally we see some examples of how to execute the Include It also shows that file is searched and loaded from the repository on each call.
Include Samples Class Name
Source Code
Name of the file to upload
ObjectManager
1.Dim objManager
2.RepositoryFolderPath=”FileServerMyRepository”
3.Include “ObjectManager.class”
4.Set ObjManager = New ObjectManager
ObjectManager.class
DateTime
1.Dim BirthDate
2.RepositoryFolderPath=”FileServerMyRepository”
3.Include “DateTime.class”
4.Set BirthDate = New DateTime
DateTime.class
ActiveDirectory
1.Dim ObjActiveDirectory
2.RepositoryFolderPath=”FileServerMyRepository”
3.Include “ActiveDirectory.class”
4.Set ObjActiveDirectory = New ActiveDirectory
ActiveDirectory.class

The scripts we will write in future articles will be based on this philosophy that we explain here and it will be our standard for the development of scripts, I hope that the explanation was clear and I appreciate your comments and suggestions for improvement.

Posted in VBscript | Tagged: | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 444 other followers

%d bloggers like this: