Category Archives: Scripting

Windows Script: “WScript.CreateObject: Could not locate automation class named “WScript.Network”


When I run my VBScript Windows Script ActiveX libraries are not loading. I was getting “WScript.CreateObject: Could not locate automation class named “WScript.Network”.

Solution:

for 32bit OS:

  1. Open command prompt
  2. Type regsvr32 c:\windows\system32\wshom.ocx
  3. Type regsvr32 c:\windows\system32\scrrun.dll

for 64bit OS:

  1. Open command prompt
  2. Type regsvr32 c:\windows\SysWOW64\wshom.ocx
  3. Type regsvr32 c:\windows\SysWow64\scrrun.dll

That’s all. Your script should now work.

PowerShell: List Active Computers from Active Directory


I had a requirement to get list of active computers from Active Directory with some stored properties in computer account like OS, OS version and OU name where the computer account exists. I have defined the active computer as if LastLogonDate is less than 60 days. Here is the script.

P.S. Your computer should be installed with Powershell ActiveDirectory module.

# 
# Name : ListActiveComputers.ps1
# Purpose: Get active computer accounts from active directory by 
# checking the last logon date. Get the properties of computer
# account (name,OS,OSverion,lastlogondate and CanonicalName)
# and save it to ActiveComputers.csv file.
#
# Written by Anand Venkatachalapathy
# Date written: 03/28/2012
#

Import-Module ActiveDirectory

# get today's date
$today = Get-Date

#Get today - 60 days (2 month old)
$cutoffdate = $today.AddDays(-60)

#Get the computer accounts filtered by lastlogondate.
# Select only required properties of the computer account
# and export it to a file
Get-ADComputer  -Properties * -Filter {LastLogonDate -gt $cutoffdate} `
| Select Name,OperatingSystem,OperatingSystemVersion, `
LastLogonDate,CanonicalName | Export-Csv ./ActiveComputers.csv

Download the script here: ListActiveComputers.ps1

PowerShell Grid view is “sooo” much better than Exchange 2010 Tracking Log viewer in browser


Exchange 2010 tracking log viewer is great, but you can copy/export the results or even sort the results for different needs. So far Exchange admins are run the get-messegetrackinglog in power shell and export to CSV file using export-csv cmdlet. It’s great, but greater idea is grid view.

I found Power shell grid view is fantastic tool to view the tracking log results. The grid view results are sortable, filterable and copy/paste-able (to Excel).

TrackingLogGridView

To use the grid view simply pipe the get-messagetrackinglog results to out-gridview like this below.

get-messagetrackinglog –Recipient:xxx@company.com -Server “Exchange-HubTransport-Server” -Start “3/1/2012 7:40:00 PM” -End “3/4/2012 7:50:00 PM” | Out-GridView

Try it, you may end up liking it.

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.