When your service account is being locked out constantly….


This might be a bad idea. But this script helps at times when an service account is being locked out constantly, you need time to figure out how it is happening.

I wrote this script and schedule to run every 5 minutes to scan my service account lockouts, unlock the account and send me an email. I saved my application was going down due to the service account lockouts. I figured out how the account was locked out.

If you are interested in this script, follow the steps below.

1. Copy and paste the following script to a notepad. Save it as WatchServiceAccount.vbs

2. On 44th line, provide your NetBIOS active directory domain name to the variable strDomainName

3. on 88th line, provide your local SMTP mail server name

4. Write a batch file and call this script by Cscript WatchServiceAccount.vbs MyServiceAccountName

5. Create a scheduled task to run your batch file.

 

‘  #####                                             #                                            
‘ #     # ###### #####  #    # #  ####  ######      # #    ####   ####   ####  #    # #    # #####
‘ #       #      #    # #    # # #    # #          #   #  #    # #    # #    # #    # ##   #   #  
‘  #####  #####  #    # #    # # #      #####     #     # #      #      #    # #    # # #  #   #  
‘       # #      #####  #    # # #      #         ####### #      #      #    # #    # #  # #   #  
‘ #     # #      #   #   #  #  # #    # #         #     # #    # #    # #    # #    # #   ##   #  
‘  #####  ###### #    #   ##   #  ####  ######    #     #  ####   ####   ####   ####  #    #   #  
‘                                                                                                  ‘

‘                      #     #                                         
‘                      #  #  #   ##   #####  ####  #    # ###### ##### 
‘                      #  #  #  #  #    #   #    # #    # #      #    #
‘                      #  #  # #    #   #   #      ###### #####  #    #
‘                      #  #  # ######   #   #      #    # #      ##### 
‘                      #  #  # #    #   #   #    # #    # #      #   # 
‘                       ## ##  #    #   #    ####  #    # ###### #    #
‘ Name: WatchServiceAccount.vbs
‘ Arguments: Service Account name

‘ E.g., CScript WatchServiceAccount.vbs serviceaccount

‘ Description: When run this script it will check speific service account is locked out or not.
‘ If the account locked out it will unlock the account and send emails to admins.

‘ Written by: Anand Venkatachalapathy
‘ Created on August 13th 2011

‘Get the passed argument and assign it to a variable
ServiceAccount = WScript.Arguments(0)

‘ Call the sub routine to check the account
CheckAccount ServiceAccount


‘ Name: CheckAccount
‘ Parameters: User Account Name
‘ Description: The sub routine checks IsAccountLocked attribute. If it is
‘ True, then Account is locked out. This sub routine will unlock the account
‘ send emails to administrators.

Sub CheckAccount(strAccount)
    ‘Provide your NetBIOS domain name here
    strDomainName = “MyADDomain”
   
    ‘Get the user account object
    Set objuser = GetObject(“WinNT://” & strDomainName & “/” & strAccount)
   
    ‘check if it is locked out..
    If objuser.IsAccountLocked Then
        ‘Yes, it is LOCKED OUT.
        Wscript.Echo strAccount & ” is locked out.”
       
        ‘Unlocked the account
        objuser.IsAccountLocked = 0
        objUser.setinfo
       
        ‘Send emails to Administrators
        Alert_Admins “Windows-Admins@Company.com”, strAccount & ” is locked out”, strAccount & ” has been unlocked by script. Please check the cause of account lock out.” & vbCrLf & vbCrLf & “–Your scripting friend”
    Else     
        ‘YAY! it not. No Worries here.
        Wscript.Echo strAccount & ” is NOT locked out.”
    End If
    Set obj = Nothing
End Sub

‘===============================================================
‘ Name:      Alert_Admins
‘ Purpose:   Send email using mail.corp.idt.com server.
‘ Input:     strTo – Who to send to, strSub – Subject of the message
‘             strBody – Body of the message
‘ Output:    Sends the emails to the strTO recipients
‘===============================================================
Sub Alert_Admins( strTo,strSub,strBody)

    ‘WScript.Echo strBody

    ‘* iMsg – holds CDO.Message object
    ‘* Flds – Enumeration for CDO SMTP object properties
    ‘* iConf – holds CDO.Configuration
    Dim iMsg, Flds, iConf

    ‘* sSMTPServerName – SMTP Server Name
    Dim sSMTpServerName

    ‘* Assign corpml servers as SMTP server
    sSMTPServerName = “smtp.company.com”

    ‘* Assign cdoSendUsingPort is set to 2, i.e., send using SMTP (25) port
    Const cdoSendUsingPort = 2

    ‘* Create CDO Objects and assign to variables
    Set iMsg = CreateObject(“CDO.Message”)
    Set iConf = CreateObject(“CDO.Configuration”)
    Set Flds = iConf.Fields

    ‘* Assign values to Flds class properties

    With Flds
        .Item(“
http://schemas.microsoft.com/cdo/configuration/sendusing”) = cdoSendUsingPort
        .Item(“
http://schemas.microsoft.com/cdo/configuration/smtpserver”) = sSMTPServerName
        .Item(“
http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout”) = 25 
        .Update
    End With

    ‘* Assign message properties and Send the mail
    With iMsg
        Set .Configuration = iConf
        .Fields(“urn:schemas:httpmail:importance”).Value = 2    ‘Setting Mail importance to High (2)
        .Fields.Update
        .To = strTo
        .From = “AccountsWatcher@company.com”               ‘Fake, but make-sense email FROM address
        .Sender = “admin@company.com”                    ‘Return Email address
        .Subject = strSub
        .TextBody = strBody
    .Send
    End With

End Sub

VBScript: Find Hostname from a IP Address


I had a requirement to find computer name from a list of IP addersses. I wrote the following vb script function for my requirement. I made it more generic function so any one can use it. Here it is.

‘Function to find Hostname from IP address. To run this function,
‘you have to be administrator to the targer computer.

‘ Function Name: HostName
‘ Parameters: IP Address as a string
‘ Returns Hostname string

Function HostName (IPAddress)
 Dim objWMI, objItem, colItems

 On Error Resume Next
 ‘ Get local WMI CIMv2 object
 Set objWMIService = GetObject(“winmgmts:\\” & IPAddress & “\root\cimv2”)
 If Err.Number <> 0 Then
  HostName = “Error”
  Err.Clear
   On Error Goto 0
  Exit Function
 End If
 On Error Goto 0

 Set colItems = objWMIService.ExecQuery(“SELECT * FROM Win32_ComputerSystem”, “WQL”, _
                                          wbemFlagReturnImmediately + wbemFlagForwardOnly)

 For Each objItem In colItems
  HostName = objItem.Name
 Next

 Set colItems = Nothing
 Set objWMI = Nothing
End Function
‘ – – – – End of Function  – – – –

Powershell: Outlook.Application access doesn’t work consistently


I was running Outlook 2010 and running an Powershell script to access emails by sub folders and count them for a weekly report. The problem was script seems to failing during testing. Sometime I get list of emails displaying, other times it was nothing.

I started my script with

$outlook = new-object -com Outlook.Application
$session = $outlook.Session

When I am done with subfolders and mail counting, my script quits right away. Seems simple, but script didn’t work correctly most of the times.

The issue was I wasn’t closing the Outlook object (outlook.application) in the script. Outlook was hanging around the memory and script was failing to open the outlook object while other object was in memory already.

Adding the following line to close the Outlook Object worked the wonders.

$outlook.Quit()

Ok I pledge I will clean up the memory in my scripts. Disappointed smile

Power shell: How to list group members?


Every system admin gets request to send list of group members from all kinds of users.  It’s very easy if you know how to search Internet (Bing! anyone).

Long back I posted VBScript to list the group members. Check here: https://anandthearchitect.wordpress.com/2008/10/18/get-members-list-from-a-domain-group-by-vbscript/

While back I posted an blog to list the AD group members using DSQuery command in Command Prompt. Check Here: https://anandthearchitect.wordpress.com/2009/12/02/get-active-directory-group-member-list/

Now we have the handy dandy power shell and Active Directory Module on latest version of Windows. Here is how you can list the group members using power shell.

1. Launch power shell

2. Import the AD module by typing

Import-Module ActiveDirectory

3. Type this command: (replace “finance” with your “AD group name”)

Get-ADGroupMember "finance" | Format-Table Name, samaccountname

Now the explanation. Get-ADGroupMember get the list of members on the specified group. We pipe that into Format-Table cmdlet which will display the results in table format. I only want Full Name and UserName of the member details.

Fixing Dead XenApp Servers automatically by script


My Citrix XenApp farm runs with XenApp 5 on Windows Server 2008 64bit servers. I found a strange issue on few XenApp Servers goes to Zombie mode. The server is pingable and operational. No users connected to this server. If you have specific application points to this server, Users get this error message:

It was not possible to launch the selected application.
Please contact your administrator
The Citrix client reported error: 12

If you run “QFarm /Load” on any one of the XenApp server in the farm, load results doesn’t list the zombie server.  ‘”Change Logon /Query” command result shows Logon is enabled. I read the available hot fixes and none of them fixes this issue.  smile_baringteeth

Easy fix is to restart “Citrix Independent Management architecture” aka IMA service on the problematic server. By restarting IMA service you are re-registering the server to the Farm. The load balancing algorithm starts accounting the server after IMA restart.

So I wrote the following script and run it by hour using Windows Scheduler on one of the XenApp server. This script sends emails details report to specified admins when it fixes the zombie server issue. Till I find a permanent fix from Citrix or Microsoft, This script is saving me from aches.

If you want to use this script, copy and paste this script to Notepad.  Look for “<<<< Modify the value here..” and change the appropriate values according to your company. Schedule it on one of your XenApp servers.

'======================================================================
' Name:      Fix-XenApp-Servers.vbs
' Purpose:   Detect if XenApp server is dropped from Load Balancing.
'            If Yes, Restart the Citrix IMA server and send email alert.
' Parameters: None
' Written By: Anand Venkatachalapathy
' Date Written: Feb 10th 2010
'====================================================================== 
 
Const IMAService = "Citrix Independent Management Architecture"
Dim WshShell, WshExec
Dim LoadData, emailSubject,emailTo,i
Public emailBody
Dim XenAppServers
 
XenAppServers = Array("CitrixSvr1","CitrixSvr2","CitrixSvr3")  '<<<<<<<<< Modify the value here
 
emailTo = "admin1@company.com;admin2@company.com"     '<<<<<<<<< Modify the value here
Set WshShell = WScript.CreateObject("WScript.Shell")
 
'Run qfarm /load command and get the results to LoadData variable
Set WshExec = WshShell.Exec("qfarm /load ") 
LoadData = LCase(WshExec.StdOut.ReadAll)
 
For i = 0 To UBound(XenAppServers)
    
    'Check if XENAPPxx server is missing
    If InStr(LoadData,LCase(XenAppServers(i))) = 0 Then
        WScript.Echo XenAppServers(i) & " is not responding"
        emailSubject = XenAppServers(i) & " was not responding, IMA service restarted"
        emailBody = XenAppServers(i) & " Server was not listed in QFarm /Load command as below" & vbCrLf
        emailBody = emailBody & LoadData & vbCrLf & vbCrLf & _
"Trying to fix by restarting IMA service to re-register to the farm" & vbCrLf & vbCrLf
        
        'Restart Citrix IMA service
        service_control XenAppServers(i),IMAService,"restart"
        
        Set WshExec = WshShell.Exec("qfarm /load ") 
        LoadData = LCase(WshExec.StdOut.ReadAll)
        
        emailBody = emailBody & "QFarm /Load results after IMA service restart" & vbCrLf
        emailBody = emailBody & LoadData
        emailBody = emailBody & vbCrLf & vbCrLf & "--------Written By: Anand Venkatachalapathy------------"
            
        'Send email to Citrix Admins
        Alert_Admins emailTo,emailSubject,emailBody
    End If
 
Next
 
'*** End of Script ***
 
 
 
 
 
 
'==============================================================================
' Name:      Service_Control
' Purpose:   Restart, Stop or Start a Service on a remote server 
' Input:     strComputer - Remote Server Name
'             sname - Service Display Name
'             purpose - has to be "stop" or "start" or "restart"
'==============================================================================
Sub Service_Control(strComputer,sname,purpose)
    'strComputer is the computer you want to connect to
    'sname is the service name
    'purpose is whether or not you want to start, stop or restart a service
    Dim delay, err_return
    delay = 20000    '20 seconds
    WScript.stdout.Write "*"
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")
    Set colListOfServices = objWMIService.ExecQuery _
            ("Select * from Win32_Service where DisplayName = '" & sname & "'")
    For Each objService In colListOfServices
        'Just to double check we have the right service
        If objService.displayname = sname Then
            WScript.stdout.Write "*"
            If purpose = "stop" Or purpose = "restart" Then
                    emailBody = emailBody & "Trying to stop " & strComputer & "" & objService.name & vbCrLf
                    err_return = objService.stopservice
                    'service has dependencies, so we need to stop those first
                    If err_return = 3 Then
                        'GOTCHA - you have to use the service.name NOT service.displayname for this query!!
                        'even if you change Win32_Service.Name to Win32_Service.DisplayName
                        Set colServiceList2 = objWMIService.ExecQuery("Associators of " _
                           & "{Win32_Service.Name='" & objService.name & "'} Where " _
                                & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
                        For Each objService2 in colServiceList2
                            emailBody = emailBody & "Trying to stop " & strComputer & "" & objService2.name & vbCrLf
                            objService2.StopService()
                            If Not objService2.state = "Stopped" Then
                                'you have to pause because the service wont start unless it is completely stopped
                                WScript.Sleep delay
                                service_control strComputer,sname,"stop"
                            Else
                                'WScript.Echo objService2.displayname & " has been stopped."
                                emailBody = emailBody & strComputer & "" & objService2.name & "has been stopped." & vbCrLf
                            End If
                        Next
                        'stop the original service that had dependencies
                        emailBody = emailBody & "Trying to stop " & strComputer & "" & objService.name & vbCrLf
                        objService.stopservice
                    Else
                        If Not objService.state = "Stopped" Then
                            'you have to pause because the service wont start unless it is completely stopped
                            WScript.Sleep delay
                            service_control strComputer,sname,"stop"
                        Else
                            'WScript.Echo objService.displayname & " has been stopped."
                            emailBody = emailBody & strComputer & "" & objService.displayname & " has been stopped." & vbCrLf & vbCrLf
                        End If
                    End If
                    'if restart was sent, start service after it has stopped
                    If purpose = "restart" Then service_control strComputer, sname, "start" End if
            Elseif purpose = "start" Then    
                    WScript.stdout.Write "*"
                    emailBody = emailBody & "Trying to start " & strComputer & "" & objService.name & vbCrLf
                    err_return = objService.startservice
                    If NOT err_return = 10 Then
                        'GOTCHA - you have to use the service.name NOT service.displayname for this query!!
                        'even if you change Win32_Service.Name to Win32_Service.DisplayName
                        Set colServiceList2 = objWMIService.ExecQuery("Associators of " _
                           & "{Win32_Service.Name='" & objService.name & "'} Where " _
                                & "AssocClass=Win32_DependentService " & "Role=Antecedent" )
                        For Each objService2 in colServiceList2
                            emailBody = emailBody & "Trying to start " & strComputer & "" & objService2.name & vbCrLf
                            objService2.StartService()
                            If Not objService2.state = "Running" Then
                                'you have to pause because the service wont start unless it is completely stopped
                                WScript.Sleep delay
                                service_control strComputer,sname,"start"
                            Else
                                WScript.Echo objService2.displayname & " has been started."
                                emailBody = emailBody & strComputer & "" & objService2.displayname & " has been started" & vbCrLf
                            End If
                        Next
                        
                        emailBody = emailBody & "Trying to start " &  strComputer & "" & objService.name & vbCrLf
                        err_return = objService.startservice
                        'service has dependencies, so we need to start those first
                        If err_return = 3 Then
                            'start the original service that had dependencies
                            emailBody = emailBody & "Trying to start " &  strComputer & "" & objService.name & vbCrLf
                            objService.startservice
                            'End If
                            If Not objService.state = "Running" then
                                'you have to pause because the service wont start unless it is completely stopped
                                WScript.Sleep delay
                                service_control strComputer,sname,"start"
                            Else
                                'WScript.Echo objService.displayname & " has been started."
                                emailBody = emailBody &  strComputer & "" & objService.displayname & " has been started." & vbCrLf
                            End If
                        End If
                    End If
                    'WScript.Echo objService.displayname & " has been started."
                    emailBody = emailBody &  strComputer & "" & objService.displayname & " has been started" & vbCrLf
            End If
        End If
    Next
 
End Sub 
'*** End of service_control sub ***
 
 
 
 
 
 
 
'======================================================================
' Name:      Alert_Admins
' Purpose:   Sends email 
' Input:     strTo - Who to send to, strSub - Subject of the message
'             strBody - Body of the message
' Output:    Sends the emails to the strTO recipients
'======================================================================
Sub Alert_Admins( strTo,strSub,strBody)
 
    'WScript.Echo strBody
 
    '* iMsg - holds CDO.Message object
    '* Flds - Enumeration for CDO SMTP object properties 
    '* iConf - holds CDO.Configuration
    Dim iMsg, Flds, iConf
 
    '* sSMTPServerName - SMTP Server Name
    Dim sSMTpServerName
 
    '* Assign corpml servers as SMTP server
    sSMTPServerName = "smtp.company.com"   '<<<<<<<<< Modify the value here
 
    '* Assign cdoSendUsingPort is set to 2, i.e., send using SMTP (25) port
    Const cdoSendUsingPort = 2
 
    '* Create CDO Objects and assign to variables
    Set iMsg = CreateObject("CDO.Message")
    Set iConf = CreateObject("CDO.Configuration")
    Set Flds = iConf.Fields
 
    '* Assign values to Flds class properties
 
    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = sSMTPServerName
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 25  
        .Update
    End With
 
    '* Assign message properties and Send the mail
    With iMsg
        Set .Configuration = iConf
        .Fields("urn:schemas:httpmail:importance").Value = 2    'Setting Mail importance to High (2)
        .Fields.Update
        .To = strTo
 
        'Fake, but make-sense email FROM address
        .From = "XenApp-Fixer@company.com"               '<<<<<<<<< Modify the value here
 
        'Return Email address
        .Sender = "XenApp-Fixer@company.com"            '<<<<<<<<< Modify the value here
        .Subject = strSub
        .TextBody = strBody
    .Send
    End With
 
End Sub
'*** End of Alert_Admins Sub ***

How to Delete folders by wildcard search? Answer: use PowerShell


I had a requirement to delete directories by wildcard. Unfortunately RMDIR  User* will not work in command prompt. I found the answer in PowerShell. The following command delete a bunch of folders by wildcard selection.
 
The following command deletes all folders starting with "2008*" under C:program FilesDBappLogs.
 
get-childitem -path ‘C:Program FilesDBappLogs’ -filter 2008* | remove-item -force -recurse
 
The follwoing command deletes all folders starting with anand* under \servernamec$documents and settings
 
get-childitem -path ‘\servernamec$documents and settings’ -filter anand* | remove-item -force -recurse
 
If it helps you, I am glad for you. smile_shades

How to get folder size of each sub folders?


Let’s just say you want to get folder size of each home folder of the users. Or trying to see which sub folders are growing fast. I use the following three ways depending on my requirement.

1. Fantastic tool named Disk Usage v1.33 by Mark Russinovich: http://technet.microsoft.com/en-us/sysinternals/bb896651.aspx

2. VBScript of my own. Copy the following script into Notepad and save as foldersize.vbs. Run the script as below:

CScript folder.vbs <folder path>

'********************************************************************************
' Script Name: foldersize.vbs
' Purpose: Display and generate a tab delimited file of subfolder names and it's
' size
' Parameter: <directory name with full path> if the path contains spaces, double
' quote the path name
'
' e.g., CScript foldersize.vbs \servernamesharename
'
' Written by: Anand Venkatachalapathy
' Created on : Jan 18 2010
'******************************************************************************** 

' Defining some variable
Dim fso
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim sLoc, LogFileName
Dim fLog, SourceLoc, sf 

' get the file system object
Set fso = CreateObject("Scripting.FileSystemObject") 

' Get the arguments of folder path
sLoc =  WScript.Arguments(0) 

' Define the log file name
LogFileName = Replace(sLoc,"","-") & ".txt" 

'Create the Log file
Set fLog = fso.OpenTextFile(LogFileName, ForWriting, True) 

'Get the sub folder list from the given path
Set SourceLoc = fso.GetFolder(sLoc)
Set sf = SourceLoc.SubFolders 

'Header for the log file
fLog.WriteLine "Folder Path" & chr(9) & "Size in MBs" 

'for each sub directory get the size
For Each SubDirs in sf
    FindFolder SubDirs.Path 
Next 

'close the log file
fLog.Close 

'**** End of Script **** 

'***********************************************************************************
' Subroutine: FindFolder (<sub-folder name with path>
' Purpose: Get the size of the given sub folder
'***********************************************************************************
Sub FindFolder (FolderSpec)
    'Get the specified folder object
    Set f1 = fso.GetFolder(FolderSpec)
    'Error processing - set if error occurs resume the script    
    On Error Resume Next 

    'Get the folder size
    fsize = f1.Size 

    'if the folder structure or any files are corrupted under this sub folder
    'getting the size will return an error
    '
    'check if we got an error,
    If Err.Number <> 0 Then
        'Yup, got an error
        Wscript.Echo f1.path & " is corrupted. Script cannot process this location."
        fLog.WriteLine f1.Path & chr(9) & "Permission Denied or Corruped files found"
        Err.Clear
    Else
        'display and log the folder name and size            
        WScript.Echo f1.Path & chr(9) & _
           FormatNumber(((fSize/1024)/1024),2)
        fLog.WriteLine f1.Path & chr(9) & _
           FormatNumber(((fSize/1024)/1024),2)
    End If
    On Error Goto 0
    Set f1 = Nothing
End Sub

3. Powershell Script. Copy and paste the following script into notepad and save it as foldersize.ps1. Open up the powershell and go the location where you want list the subfolders and its size and run this script.

# Script: foldersize.ps1
# Usage: Change the working directory where you want to list get size of the folders
# Run the script as c:<dir where this script exists>foldersize.ps1 
# If you want to create a file with the results of this code, run this script as
# C:<dir where this script exists>foldersize.ps1 > homefolders.txt
#
# Written by Anand Venkatachalapathy
# Date Written: Jan 18 2010 

#Get the directory listing and pass the resutls to ForEach 
get-childitem | where {$_.PSIsContainer} | foreach { 

#For every subfolder get the size 
$size = (Get-ChildItem $_ -recurse | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum 

#add the sub folder path and size into table
$obj = new-object psobject
add-member -inp $obj noteproperty path $_.fullName
add-member -inp $obj noteproperty size $size 

#display the table
$obj 

}
#End of Script

Search tags: FolderSize, directory size, vbscript, powershell

Map Network drive with different credentials in command line


One of these wonderful days, I came across a need to map a network drive before I run a script. It’s a hassle to manually create the network drive mapping every time. This is because I was using different credentials to map the network drive.

Then I put my mask, and yelled “This is the job for…scripting man!!!”. Nerd

Here is my VBScript to map the network drive with different credentials without user interaction. Hope it is useful for somebody else. Make sure you type the correct server URL, drive letter and credentials in this script before you run.

‘*******************************************************************************
‘ Script Name: MapNetwork.vbs
‘ Purpose: Map network drive with different credentials
‘ Usage: Change the values for SDrive, sNetworkLocation, sUser, sPassword
‘        variables and run the script. Script returns nothing, but it will
‘        map the network drive to the specified drive letter.

‘ Author: Anand Venkatachalapathy
http://anandpv.spaces.live.com
‘********************************************************************************

Dim oNetwork
Dim sDrive, sNetworkLocation, sUser, sPassword

sDrive = "W:"
sNetworkLocation = "\MyServerData"
sUser = "MyDomainMyUserName"
sPassword = "MyPassword"

Set oNetwork = CreateObject("wscript.network")

oNetwork.MapNetworkDrive sDrive,sNetworkLocation,False,sUser,sPassword

Set oNetwork = Nothing

‘******************* End of Script *************

VBScript: List installed printers list


Today I had to get the list of printer drivers installed on various servers. I wrote a quick and dirty script to get the printer list.

If you want to use this, copy the following script text and paste it in Notepad. Save it as “PrinterList.vbs”. Run it as,

C:> CSCript PrinterList.vbs <Your Server Name>

‘**************************************************************************
‘ Script Name: PrinterList.vbs
‘ Parameter: Computer Name
‘ Syntax: CScript PrinterList.vbs <Computer Name>

‘ Written By: Anand Venkatachalapathy
http://anandpv.spaces.live.com
‘**************************************************************************

Dim strComputer, i
Dim objWMIService, colInstalledPrinters

‘If there are no arguments pass, quit the script
If WScript.Arguments.Count = 0 Then
    WSCript.Echo "No Server/computer name specified…"
    WScript.Echo "Syntax: CScript PrinertList.vbs <ComputerName>" & vbCrLf
    WSCript.Echo "Example: CScript PrinterList PrintServer1"
    WScript.Quit
End If

strComputer = WScript.Arguments(0)

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_PrinterDriver")

i = 1

WScript.Echo strComputer & ": Installed Printer Drivers…"
WScript.Echo "———————————————————-"
For each objPrinter in colInstalledPrinters
    Wscript.Echo i & ": " & objPrinter.Name
    i = i + 1
Next

Set colInstalledPrinters = Nothing
Set objWMIService = Nothing

‘**************************** End of Script ************************

Keywords: List installed printer drivers, List printers, Printer List

Find OS Type using VBScript (ready to use VBScript Function, right here)


If you looking to find a computer or server’s OS type using VBScript, you can use my ready to use function as below.

‘///////////////////////////////////////
‘ Function: FindOSType
‘ Parameter: Computer Name
‘ Purpose: This function return the OS name of the provided computer for all
‘ Windows OS machines

‘ Written by: Anand Venkatachalapathy (http://anandpv.spaces.live.com)
‘///////////////////////////////////////

Function FindOSType(ComputerName)
    ‘Defining Variables
    Dim objWMI, objItem, colItems
    Dim OSVersion, OSName, ProductType

    ‘Get the WMI object and query results
    Set objWMI = GetObject("winmgmts:\" & ComputerName & "rootcimv2")
    Set colItems = objWMI.ExecQuery("Select * from Win32_OperatingSystem",,48)

    ‘Get the OS version number (first two) and OS product type (server or desktop)
    For Each objItem in colItems
        OSVersion = Left(objItem.Version,3)
        ProductType = objItem.ProductType
    Next

    ‘Time to convert numbers into names
    Select Case OSVersion
        Case "6.0" 
            OSName = "Windows Vista"
        Case "5.2" 
            OSName = "Windows 2003"
        Case "5.1" 
            OSName = "Windows XP"
        Case "5.0" 
            OSName = "Windows 2000"
        Case "4.0" 
            OSName = "Oh! Really! NT 4.0"
        Case Else
            OSName = "Hi! Grandpa! Windows ME or older"
    End Select

    ‘Return the OS name
    FindOSType = OSName
   
    ‘Clear the memory
    Set colItems = Nothing
    Set objWMI = Nothing
End Function