Immediate Solutions


Using Logs with Shell Scripting

Currently, shell scripting contains no built-in methods to access the event log. Fortunately, you can create your own text logs or use resource kit utilities to access the event log.

Writing to Text Logs

The simplest way to log events in shell scripting is to append text to a text log. The basic syntax to append text to a text log is as follows :

  Command  >>  textlog  

Here, command is either an echoed statement or the output of a command, and textlog is the complete path and file name of the log file. Here is a quick example to send a message to a log file called log.txt:

 @Echo Off Echo This is a test to log an event. >> log.txt 
Tip  

To clear the log, simply delete the file ( DEL textlog ).

Related solution:

Found on page:

Appending Text Files

57

Writing to Text Logs with the Date and Time

Recording the date and time within a log is essential to determine the exact moment of a particular event. To place the date and time into an environment variable using shell scripting, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Select StartRun and enter " scriptfile .bat."

Here, scriptfile is the full path and file name of a script file that contains the following:

 @Echo Off  For /F "Delims= Tokens=1" %%  I  in ('Date /T') Do Set  Dtime  =%%  I    For /F "Delims= Tokens=1" %%  I  in ('Time /T') Do Set  Dtime  =%Dtime%%%  I   
Note  

The highlighted code above must be placed on one line.

To log an event using the date and time, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Copy the date time script above to a file called SETDTIME.BAT.

  3. Select StartRun and enter " scriptfile .bat."

Here, scriptfile is the full path and file name of a script file that contains the following:

 Call setdtime.bat Echo %  Dtime  %  message  >>  textlog  

Here, message is the alert message to log, and textlog is the complete path and file name of the log file.

Tip  

To clear the date and time variable ( dtime ), add the following line at the end of your entire script: SET %Dtime%=.

Using LOGEVENT to Write to the Event Log

LOGEVENT.EXE is a Windows 2000 resource kit utility to write events to the event log from the command line. The basic syntax of LOGEVENT.EXE is as follows:

  logevent -m \  computer  -s  type  -c  category  -r  source  -e  id  -t  time  "  message  "  
Note  

The highlighted code above must be placed on one line.

Here, computer is the name of a remote system to connect to; source specifies the origin of the event; id indicates the entry ID number (0-65535); category is the number for the desired category; message is the text to include in the entry; time is the amount of seconds the system waits before an exit; and type specifies one of the following event types:

  • E ”Error

  • F ”Failure

  • I ”Information

  • S ”Success

  • W ”Warning

Tip  

LogEvent will accept either the full name or the first letter of the event type. Example, you can specify -S ERROR or -S E .

Here is an example of how to write an event to the event log:

 logevent -S ERROR -C 3 -E 10 -R ShellScript "Some Event Text" 

Using EVENTCREATE to Write to the Event Log

EVENTCREATE.EXE is a built-in Windows XP/2003 utility to write events to the event log from the command line. The basic syntax of EVENTCREATE.EXE is as follows:

  eventcreate /s  computer  /u  domain\username  /p  password  /t  type  /l  logname  /so  source  /Id  eventid  /d "  message  "  
Note  

The highlighted code above must be placed on one line.

Here, computer is the name of a remote system to connect to; domain\username and password specifies the credentials to use when writing the event; source specifies the origin of the event; eventid indicates the entry ID number (0-65535); logname is the name of the event log to write to; message is the text to include in the entry; and type specifies one of the following event types:

  • Error

  • Information

  • Warning

Here is an example of how to write an event to the event log:

 eventcreate /t ERROR /l application /so SHELLSCRIPT /Id 10 /d  "Some Event Text" 

Using Dumpel to Back Up the Event Log

Dumpel is a Windows 2000 resource kit utility that allows you to back up an event log in text format from the command line. The basic syntax for using Dumpel is as follows:

 Dumpel -F  textfile  -L  logtype commands  

Here, textfile is the complete path and file name to back up the event log to; logtype is the type of log to back up (Application, System, or Security); and commands are any of the following optional commands:

  • -D days ”Displays only the last number of days specified where days must be larger than zero

  • -E ID ”Displays only the specified event ID s where ID may be up to ten various event IDs

  • -M name ”Displays only the events with the name specified

  • -R ”Specifies to filter by sources of records

  • -S computer ”Specifies the computer to connect to

  • -T ”Separates values using tabs as opposed to spaces

To back up security log events from the past ten days using Dumpel, start a command prompt and enter the following:

 Dumpel -F "C:\DUMP.TXT" -L "Security" -D 10 

Using Logs with KiXtart

KiXtart provides several methods to write text logs and to access the event log. Through KiXtart, you can write to, back up, and clear the event logs.

Writing to Text Logs

Text logs allow all users, regardless of operating system, to write, modify, and read logged events. To log an event to a text log using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

  $RCODE  = Open(1, "  textlog  ", 5)   $RCODE  = WriteLine(1, @Date + " " + @Time + "  message  " + Chr(13) + Chr(10))   $RCODE  = Close(1) 
Note  

The highlighted code above must be placed on one line.

Here, message is the alert message to log, and textlog is the complete path and file name of the log file. Notice that the first line opens and sets the text log to file number 1, the next line writes to file number 1, and then the final line closes file number 1. All three steps are necessary to write to a text file. Failure to include the close statement will result in wasted memory space.

Tip  

To clear the log, simply delete the file ( DEL textlog ).

Related solution:

Found on page:

Appending Text Files

57

Writing an Event to the Event Log

LogEvent is a KiXtart command that allows you to write entries to the event log. The basic syntax for using the LogEvent command is as follows:

 LOGEVENT (  type  ,  ID  ,  event  ,  computer  ,  source  ) 
Note  

All events are stored in the application log and cannot be redirected to the system or security logs.

Here, ID is the entry ID number to assign; event is the text event entry; computer is an optional parameter specifying the name of a remote system to write events to; source specifies the event source; and type specifies one of the following event types:

  • ”SUCCESS

  • 1 ”ERROR

  • 2 ”WARNING

  • 4 ”INFORMATION

  • 8 ”AUDIT_SUCCESS

  • 16 ”AUDIT_FAILURE

To write an event to the event log using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

   $RCODE  = LogEvent(0, 10, "This stuff is easy!", "", "New Event")  If @ERROR <> 0 or  $RCODE  <> 0   ? "Error writing event" EndIf 
Note  

The highlighted code above must be placed on one line.

Backing Up the Event Log

BackUpEventLog is a KiXtart command that allows you to back up the event log in the standard event log binary format. The basic syntax for using the BackUpEventLog command is as follows:

 BackUpEventLog ("  logtype  ", "  textfile  ") 

Here, logtype is the type of log to back up (Application, System, or Security), and textfile is the complete path and file name to back up the event log to. To back up the security log to a file called Backup.evt using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

  $RCODE  = BackUpEventLog ("Security", "C:\BACKUP.EVT") If @ERROR <> 0 or  $RCODE  <> 0   ? "Error backing up log" EndIf 

Clearing the Event Log

ClearEventLog is a KiXtart command that allows you to clear the contents of an event log. The basic syntax for using the ClearEventLog command is as follows:

 ClearEventLog ("  logtype  ") 
Tip  

You can clear the event log of a remote computer by including the UNC path before the log type, for example: ClearEventLog ("\\ computer \ Security ").

Here, logtype is the type of log to clear (Application, System, or Security). To clear the event log using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

  $RCODE  = ClearEventLog ("Security") If @ERROR <> 0 or  $RCODE  <> 0   ? "Error clearing the event log" EndIf 

Using Logs with Windows Script Host

Windows Script Host allows you to write events to a text log and the event log using simple script files. This allows you to store critical events in the event log, while storing less severe events to a text log.

Note  

Windows Script Host does not contain any methods to read or modify events in the event log.

Writing to Text Logs

Text logs provide an easy way to record events and share the file with others, regardless of operating system. To log an event to a text log using Windows Script Host, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next Set  FSO  = CreateObject("Scripting.FileSystemObject")  txtlog  = "  textlog  " If  FSO  .FileExists(  txtlog  ) Then   Set  LogFile  =  FSO  .OpenTextFile(  txtlog  , 8) Else   Set  LogFile  =  FSO  .CreateTextFile(  txtlog  , True) End If  LogFile  .WriteLine Date & " " & Time & "  message  "  LogFile  .Close 

Here, message is the alert message to log, and textlog is the complete path and file name of the log file.

Related solution:

Found on page:

Appending Text Files

57

Writing an Event to the Event Log

You can use Wscript.Shell's LogEvent method to write events to the event log. The basic syntax for using the LogEvent method is as follows:

 LogEvent(  type  ,  event  ,  computer  ) 
Note  

All events are stored in the application log, and cannot be redirected to the system or security logs.

Here, event is the text event entry; computer is an optional parameter specifying the name of a remote system to write events to; and type specifies one of the following event types:

  • SUCCESS (0)

  • ERROR (1)

  • WARNING (2)

  • INFORMATION (4)

  • AUDIT_SUCCESS (8)

  • AUDIT_FAILURE (16)

Tip  

You can use the corresponding numbers , as opposed to key words, to specify event types.

When you use LogEvent to create an event log entry, the following is recorded:

  • Category ”Logged as None

  • Computer ”The name of the target computer

  • Date ”Date the event was written

  • Event ”Logged as 0

  • Source Type ”Logged as WSH

  • Time ”Time the event was written

  • Type ”Type of event entry

  • User Name ” Logged as N/A

Here is a subroutine to write an event:

 Sub WriteLog(  Ltype  ,  Ldesc  )   On Error Resume Next   Set  SHELL  = CreateObject("WScript.Shell")  LEvent  =  SHELL  .LogEvent(  Ltype  ,  Ldesc  )   If Err.Number <> 0 Or  LEvent  = False Then     Wscript.Echo "Error writing event"   End If End Sub 
Note  

Because Windows 9x does not contain an event log, all written events will be stored in %WINDIR%\wsh.log.

Here, ltype is the type of event, and ldesc is the event text to write. Using the following command combined with the subroutine above will write a success event to the event log:

 WriteLog 0, "This stuff is cool!" 

Accessing the Event Log Using WMI

The Win32_NTLogEvent class manages the event logs on Windows 2000/XP/2003 systems. Through this class, you can view, write, modify, delete, and back up the event log through simple scripts.

Backing Up an Event Log in Binary Mode

The BackupEventLog method allows you to back up an event log to a file in standard event log binary format. To create a backup of the event log in standard event log binary format using WMI, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next Set  FSO  = CreateObject("Scripting.FileSystemObject")   LogType  = InputBox("Enter the log to backup", "Log Type" , "application")    BFile  = InputBox("Enter file to backup to", "Backup File" , "C:\BACKUP.LOG")  If  FSO  .FileExists(  BFile  ) Then  FSO  .DeleteFile  BFile  End If  Set  EventLog  = GetObject("winmgmts:{impersonationLevel= impersonate,(Backup)}").ExecQuery("select * from Win32_NTEventLogFile where LogfileName='" &  LogType  & "'")  For each  Entry  in  EventLog   Entry  .BackupEventLog  BFile  Next Wscript.Echo "Done" 
Note  

The highlighted code above must be placed on one line. The (Backup) privilege is explicitly included in the example above to allow you to use the BackUpEventLog method.

Here, LogType is the event log to back up (application, security, or system), and Bfile is the complete path and filename to back up to.

Backing Up the Entire Event Log in Text Mode

In the previous sections, you learned that the BackUpEventLog method and the Dumpel utility back up the event log to a text file in binary format. Although this format conforms to the standard event log storage format, it does not allow you to easily view the contents of the backup. To create a backup of the event log in plain-text, tabdelimited format using WMI, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next  Set  EventLog  = GetObject("winmgmts:{impersonationLevel= impersonate}").ExecQuery("select * from Win32_NTLogEvent")  Set  FSO  = CreateObject("Scripting.FileSystemObject") Set  txt  =  FSO  .CreateTextFile("  textfile  ", True) For each  Entry  in  EventLog  If Len(  Entry  .Message) > 0 Then     For  x  = 1 to Len(  Entry  .Message)  Char  = Mid(  Entry  .Message,  x  ,1)       If Asc(  Char  ) = 10 Then  MSG  =  MSG  & " "       ElseIf Asc(  Char  ) <> 13 Then  MSG  =  MSG  &  Char  End If     Next  EDate  = Mid(  Entry  .TimeGenerated,5,2) & "/" & _       Mid(  Entry  .TimeGenerated,7,2) & "/" & _       Mid(  Entry  .TimeGenerated,1,4)  ETime  = Mid(  Entry  .TimeGenerated,9,2) & ":" & _       Mid(  Entry  .TimeGenerated,11,2) & ":" & _       Mid(  Entry  .TimeGenerated,13,2)  ETime  = FormatDateTime(  ETime  ,3)     IfIsNull(  Entry  .User) Then  User  = "N/A"     Else  User  =  Entry  .User     End If     IfIsNull(  Entry  .CategoryString) Then  Category  = "none"     Else  Category  =  Entry  .CategoryString     End If  EVT  =  Entry  .LogFile & VBtab & _  Entry  .Type & VBtab & _  EDate  & VBtab & _  ETime  & VBtab & _  Entry  .SourceName & VBtab & _  Category  & VBtab & _  Entry  .EventCode & VBtab & _  User  & VBtab & _  Entry  .ComputerName & VBtab & _  MSG   txt  .writeline  EVT   EVT  = Null  Char  = Null  MSG  = Null   End If Next  txt  .close Wscript.echo "Done" 
Note  

The highlighted code above must be placed on one line.

Here, textfile is the complete path and file name to back up the event log to.

Clearing an Event Log

The ClearEventLog method allows you to clear individual event log entries. To clear the entire contents of an event log using WMI, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next   LogType  = InputBox("Enter the log to clear", "Clear Log" , "application")   Set  EventLog  = GetObject("winmgmts:{impersonationLevel= impersonate}").ExecQuery("select * from Win32_NTEventLogFile where LogfileName='" &  LogType  & "'")  For each  Entry  in  EventLog   Entry  .ClearEventlog() Next Wscript.Echo "Done" 
Note  

The highlighted code above must be placed on one line.

Here, LogType is the event log to clear (Application, Security, or System).

Sending Alerts Using Shell Scripting

Shell scripting does not include a method to send alerts from the command line. Microsoft Windows includes the NET.EXE utility to allow you to send messages to users or computers over the network.

Sending Alerts to a Single User or Computer

To send a message over the network, start a command prompt and enter the following:

 NET SEND  name message  
Note  

NetBIOS messages have a maximum limit of 128 characters .

Here, message is the message to send, and name is the NetBIOS name of a computer or user ID.

Sending Alerts to Multiple Users and Computers

You can also use the asterisk symbol (*) to send messages to all computers on the local network:

 Net Send *  message  

Here, message is the message to send. As opposed to specifying a name or asterisk, you can use one of the following commands to send messages to multiple users or computers:

  • /DOMAIN ”Sends a message to the local domain

  • /DOMAIN: name ”Sends a message to a specified domain

  • /USERS ”Sends messages to users connected to the server

Here is an example to send a message to the JESSEWEB domain:

 Net Send /DOMAIN:JESSEWEB  message  
Note  

Sending messages to the entire network or domain will not only utilize a good portion of your network's bandwidth but it is also annoying to all the other users.

Sending Alerts to Specific Multiple Users and Computers

Although the Net Send command contains methods to send messages to multiple users, it does not contain a method to send messages to specific user and computer names. To send an alert to an exact list of user or computer names using shell scripting, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Select StartRun and enter " scriptfile .bat."

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

 @Echo Off  For /F  %%N  in (  textfile  ) Do (Echo Sending Message to  %%N  ... & Net Send  %%N Message  )  
Note  

The highlighted code above must be placed on one line.

Here, textfile is the name of a text file with each line containing a user or computer name, and message is the message to send.

Sending Alerts Using KiXtart

KiXtart includes a command called SendMessage that allows you to send NetBIOS messages to users or computers over the network. This command transports messages in a similar fashion to the Microsoft NET.EXE utility.

Sending Alerts to a Single User or Computer

To send an alert to a single user using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

  $RCODE  = SENDMESSAGE ("  name  ", "  message  ") If @ERROR <> 0 or  $RCODE  <> 0   ? "Error sending message" EndIf 

Here, name is the user or computer name to send a message to.

Sending Alerts to Multiple Users or Computers

To send an alert to multiple users using KiXtart, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and extract the latest version of KiXtart, from http://www.kixtart.org, to the new directory.

  3. Select StartRun and enter "kix32 scriptfile. "

Here, scriptfile is the full path of the new directory from step 1 and file name of a script file that contains the following:

  $COUNT  = 4 ; User Array Count DIM  $NAME  [  $COUNT  ] ; User Array  $NAME  [0] = "  name1  "  $NAME  [1] = "  computer1  "  $NAME  [2] = "  computer2  "  $NAME  [3] = "  name2  "  $NETMESSAGE  = "This is a test message."  $Index  = 0 WHILE  $Index  <>  $COUNT   $RCODE  = SENDMESSAGE (  $NAME  [  $Index  ],  $NETMESSAGE  )   If @ERROR <> 0 or  $RCODE  <> 0     ? "Error sending message"   EndIf  $Index  =  $Index  + 1 LOOP 

Here, $count is the size of the array. This is the number of users you want to send messages to. This number must exactly match the number of users that you send messages to, or an error will result. $name is the array that holds the user or computer names to send messages to, and $netmessage is the message to send.

Note  

The array size is limited to the amount of memory the system has. Remember, the contents of an array start at 0, not at 1. Using versions older than KiXtart 3.62 will cause a script error when attempting to create an array.

Sending Alerts Using Windows Script Host

Windows Script Host does not include any methods to send messages to users or computers. Through Windows Script Host, you can call upon the NET.EXE utility or use automation to send messages.

Sending an Alert to a Single User or Computer

To send an alert to a single user or computer using WSH, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next Set  Shell  = CreateObject("Wscript.Shell")  RCV  = "  name  "  MSG  = "  message  "  SHELL  .Run "Net Send " &  Name  & " " &  MSG  , 0, False 

Here, RCV is the user or computer name to send a message to, and MSG is the message to send.

Sending Alerts to Multiple Users or Computers

To send an alert to multiple user or computer names using WSH, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next Set  Shell  = CreateObject("Wscript.Shell") Dim  Name  (2)  Name  (0) = "  name1  "  Name  (1) = "  name2  "  MSG  = "  message  " For  X  = 0 to UBound(  Name  )  SHELL  .Run "Net Send " &  Name  (  X  ) & " " &  MSG  , 0, False Next 

Here, Name is the array that holds the user or computer names to send messages to. The size of this array should be equal to the number of users or computers you want to send messages to. MSG is the message to send.

Sending an Email Using Outlook Automation

To send an email using Outlook automation, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next  RCP  = "  emailaddress" SUB  = "  subject  "  MSG  = "  message  " Set  Outlook  = CreateObject("Outlook.Application") Set  MAPI  = Outlook.GetNameSpace("MAPI") Set  NewMail  =  Outlook  .CreateItem(0)  NewMail  .Subject =  SUB   NewMail  .Body =  MSG   NewMail  .Recipients.Add  RCP    MAPI  .Logon "  profile  ", "  password  "   NewMail  .Send   MAPI  .Logoff  

Here, RCP stores the email address to email; SUB is the email subject ; MSG is the message to send; and profile and password are the logon credentials to send the email.

Tip  

You can omit the highlighted lines above if you do not need to log on to a mail server or if your information is cached.

Sending an Email with Attachments Using Outlook Automation

To send an email to multiple users with attachments using Outlook, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next  RCP  = "  emailaddress  " Dim  File  (2)  File  (0) = "  file1  "  File  (1) = "  file2  "  SUB  = "  subject  "  MSG  = "  message  " Set  Outlook  = CreateObject("Outlook.Application") Set  MAPI  = Outlook.GetNameSpace("MAPI") Set  NewMail  =  Outlook  .CreateItem(0)  NewMail  .Subject =  SUB   NewMail  .Body =  MSG   NewMail  .Recipients.Add  RCP  For  X  = 0 to (UBound(  File  )-1)  NewMail  .Attachments.Add(  file  (  X  )) Next   MAPI  .Logon "  profile  ", "  password  "   NewMail  .Send   MAPI  .Logoff  

Here, file is the array that holds the file names to attach to the message; RCP stores the email address to email; SUB is the email subject ; MSG is the message to send; and profile and password are the logon credentials to send the email.

Tip  

You can omit the highlighted lines above if you do not need to log on to a mail server or if your information is cached.

Sending Emails and Attachments to Multiple Recipients Using Outlook Automation

To send an email to multiple users with attachments using Outlook, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next Dim Name(2) Name(0) = "  emailaddress1  " Name(1) = "  emailaddress2  " Dim  File  (2)  File  (0) = "  file1  "  File  (1) = "  file2  "  SUB  = "  subject  "  MSG  = "  message  " Set  Outlook  = CreateObject("Outlook.Application") Set  MAPI  = Outlook.GetNameSpace("MAPI") Set  NewMail  =  Outlook  .CreateItem(0)  NewMail  .Subject =  SUB   NewMail  .Body =  MSG  For  X  = 0 to (UBound(  Name  )-1)  NewMail  .Recipients.Add  Name  (  X  ) Next For  X  = 0 to (UBound(  File  )-1)  NewMail  .Attachments.Add(  file  (  X  )) Next   MAPI  .Logon "  profile  ", "  password  "   NewMail  .Send   MAPI  .Logoff  

Here, name is the array that holds the email addresses to email; file is the array that holds the file names to attach to the message;

SUB is the email subject ; MSG is the message to send; and profile and password are the logon credentials to send the email.

Tip  

You can omit the highlighted lines above if you do not need to log on to a mail server or if your information is cached.

Sending an Email Using CDOSYS

Collaboration Data Objects for Windows (CDOSYS) is a built-in messaging object library (CDOSYS.dll) which allows developers and scripters to send email on Windows 2000/XP/2003 without having Outlook or any other email client installed. To send an email using CDOSYS, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next  RCP  = "  emailaddress  "  FROM  = "  myemailaddress  "  SUB  = "  subject  "  MSG  = "  message  " Set  NewMail  = CreateObject("CDO.Message")  NewMail  .Subject = SUB  NewMail  .Sender =  FROM   NewMail  .To =  RCP   NewMail  .TextBody =  MSG   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "  mailserver  "   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/authenticate") = 1   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "  username  "    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "  password  "    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration smtpconnectiontimeout") = 60   NewMail  .Configuration.Fields.Update  NewMail  .Send 
Note  

The highlighted code above must be placed on one line.

Here, FROM stores the email address of the sender; RCP stores the email address to email; SUB is the email subject ; MSG is the message to send; mailserver is the name or IP address of your email server; and username and password are the logon credentials to send the email.

Sending an Email with Attachment Using CDOSYS

To send an email with attachment using CDOSYS, proceed as follows:

  1. Create a new directory to store all files included in this example.

  2. Download and install the latest version of Windows Script Host, from http://www.microsoft.com, to the new directory.

  3. Select StartRun and enter "cscript scriptfile .vbs."

Here, scriptfile is the full path and file name of a script file that contains the following:

 On Error Resume Next  RCP  = "  emailaddress  "  FROM  = "  myemailaddress  "  SUB  = "  subject  "  MSG  = "  message  "  ATCH="attachmentfilepath"  Set  NewMail  = CreateObject("CDO.Message")  NewMail  .Subject = SUB  NewMail  .Sender =  FROM   NewMail  .To =  RCP   NewMail  .TextBody =  MSG   NewMail  .AddAttachment =  ATCH    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "  mailserver  "   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/authenticate") = 1   NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "  username  "    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "  password  "    NewMail  .Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration smtpconnectiontimeout") = 60   NewMail  .Configuration.Fields.Update  NewMail  .Send 
Note  

The highlighted code above must be placed on one line.

Here, FROM stores the email address of the sender; RCP stores the email address to email; SUB is the email subject ; MSG is the message to send; ATCH stores the file path of the attachment to send; mailserver is the name or IP address of your email server; and username and password are the logon credentials to send the email.




Windows Admin Scripting Little Black Book
Windows Admin Scripting Little Black Book (Little Black Books (Paraglyph Press))
ISBN: 1933097108
EAN: 2147483647
Year: 2004
Pages: 89

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net