Home > General > Executing CATIA scripts in batch mode

Executing CATIA scripts in batch mode

September 26, 2010 Leave a comment Go to comments

I got the idea for this article from a reader of this blog.  He sent me an email asking what would be the best way to extract some information from thousands of drawings in an automated way.  That information in his scenario is the value of a handful of parameters that are attached to the root drawing node in each drawing.  I recommended to execute a script in batch mode that would open each drawing one by one and read those parameter values and write the data to a text file.

In our email exchanges, we both agreed that this seemed like a great topic to share with everyone for a few reasons.  First, this is a relatively common scenario so many people could benefit by sharing the code that opens the drawings and writes out the parameter values.  Also, I have a feeling that many have never run a script in batch mode so this article might unlock some new capabilities.  So in this article, I will discuss the basics of running a batch and share the code we developed and tested.

What is batch mode?

When you start up CATIA on a typical day to do your work, you are running in interactive mode.  Interactive mode means that you see CATIA and its user interface on the screen.  You are able to click commands, select things and interact with it.  On the other hand, batch mode is a way to start CATIA without any user interface.  Obviously there are limited use cases where this would be a good idea since CATIA is running “behind the scenes” and you can’t see anything on the screen.  Typically, the reasons to use batch mode are to run CATIA utilities (See Tools-Utility menu item) or to execute a script.

Why use batch mode?

So when should you consider running a script in batch mode?  I think it is likely to be a good choice over running the script in interactive mode when:

  • You need to do some operations on a lot of separate CATIA files
  • You need to generate a lot of new data (geometry creation, product structure creation, etc.)
  • You need the best possible performance (speed)
  • No user interaction is required for the script to do its job.

One of the key items above is that CATIA will run considerably faster in batch mode than it does in interactive mode.  This is because when it runs in interactive mode, it constantly has to process updates to the interactive graphical display but in batch mode none of those updates are done.  At the end of this article, I will share the performance numbers for the drawing example batch.

The last item (no user interaction required) is very important.  Your program must be able to make all of its own decisions without any user interactions or else the batch will not be successful.  So if you have an existing program that you would like to try as a batch you should check very carefully for this and fix any potential issues.  This might mean hard coding values or decision logic into the program or making the program read input information from a text file or possibly even passing arguments into the script when the batch is launched.  These scenarios won’t be covered in this article because the example code I will share does not require any user input.

The example scenario and script

As mentioned earlier, our scenario is to open thousands of drawings and extract some parameter values and write them to a text file.  We want to do this as efficiently as possible since there are thousands of  files to process.   The parameters we need to access exist on the root parameters collection of each drawing.  All of the drawings will be located in a single folder on the local file system.  The program should be flexible enough so that we can easily specify a list of parameter names whose values should be retrieved from each drawing without having to modify the code each time the script is used.

I am not going to explain how the script works because the focus of this article is running a batch not this specific script.  However, I did add some brief comments throughout the code to aid in understanding what the macro is doing.  Take a little time and read through it because there are some interesting things in it.

If you want to try the script yourself either in interactive mode or batch, simply make some drawings that have one or more parameters in their root parameters set.  Then just edit the variables at the start of the script to specify the parameter name(s) you want to look for and the folder where the drawing files exist.

Here is the code,

' Author:
'   Mike Berry
'   Published on CATIA V5 Automation blog (v5vb.wordpress.com)
'   Send comments and feedback to blogv5vb@gmail.com
' Purpose:
'   This program will open every CATDrawing in the specified folder one by one
'   and retrieve the requested parameter values and write them to a text file
'   This program should be run as a batch if many drawings are to be processed.
' History:
'   Version     Date        Comment
'   1.0         09/26/10    First version

' Notes:
'   1. You must set the two input values below before running the script
'	 where it says, "Define input values for this batch run"
'		FOLDER	This is the full path of the folder to be processed
'		PARAMNAMES 	This is a comma separated list of parameter names
'				whose value should be retrieved

Option Explicit

Sub CATMain()

    Dim objFolder As Object
    Dim intIndex As Integer
    Dim intIndex2 As Integer
    Dim objFile As File
    Dim objDwgDoc As Document
    Dim objParams As Parameters
    Dim strParamName As String
    Dim varParamNames As Variant
    Dim strOutputValues As String
    Dim intArraySize As Integer
    Dim strOutputFilePath As String
    Dim objTextStream As TextStream
    Dim strOutput As String
    Dim objFileSystem As Object
    Dim strTimeStamp As String
    Dim lngNbDwgs As Long

    'Define input values for this batch run
    Const FOLDER As String = "C:\Temp\BatchTest"
    Const PARAMNAMES As String = "TestString,TestLength,TestMass"

    'Make sure the requested folder exists
    If CATIA.FileSystem.FolderExists(FOLDER) = False Then Exit Sub

    'Create a header in the output string
    strOutput = "Folder processed: " & FOLDER & Chr(13)
    strOutput = strOutput & "Parameter names: " & PARAMNAMES & Chr(13) & Chr(13)
    strOutput = strOutput & "File #" & Chr(9) & "Drawing name" & Chr(9) & Replace(PARAMNAMES, ",", Chr(9)) & Chr(13)

    'Create an array from the list of parameter names
    'If there is only one name, manually create the array
    'otherwise split the string into an array based on the commas
    If InStr(1, PARAMNAMES, ",") > 0 Then
        varParamNames = Split(PARAMNAMES, ",")
        ReDim varParamNames(0)
        varParamNames(0) = PARAMNAMES
    End If
    intArraySize = UBound(varParamNames)

    'Process each CATDrawing in the specified folder
    lngNbDwgs = 0
    Set objFolder = CATIA.FileSystem.GetFolder(FOLDER)
    If objFolder.Files.Count > 0 Then
        For intIndex = 1 To objFolder.Files.Count
            Set objFile = objFolder.Files.Item(intIndex)
            If UCase(Right(objFile.Name, 11)) = ".CATDRAWING" Then

                'Count the number of drawing processed
                lngNbDwgs = lngNbDwgs + 1

                'Open the drawing and get at the root parameters
                Set objDwgDoc = CATIA.Documents.Open(objFile.Path)
                Set objParams = objDwgDoc.Parameters.RootParameterSet.AllParameters

                'Append the drawing name to the output string
                strOutput = strOutput & lngNbDwgs & Chr(9)
                strOutput = strOutput & objDwgDoc.Name & Chr(9)

                'Get the value of each requested parameter and
                'append them to the output string
                For intIndex2 = 0 To intArraySize
                    strParamName = Trim(varParamNames(intIndex2))
                    strOutput = strOutput & Chr(9) & GetParameterValue(objParams, strParamName)
                strOutput = strOutput & Chr(13)

                'Close the drawing

            End If
    End If

    'If no drawings were processed, make a note in the output string
    If lngNbDwgs = 0 Then strOutput = strOutput & "No CATDrawings were found!"

    'Create a timestamp for the output text file by removing invalid chars from
    'the current date and time string that is returned by the Now() function
    'This is an easy way to guarantee a new file each time the batch is executed
    strTimeStamp = Replace(Now, "/", "-")
    strTimeStamp = Replace(strTimeStamp, ":", "-")
    strTimeStamp = Replace(strTimeStamp, " ", "_")

    'Create a new output text file and write the output string
    strOutputFilePath = objFolder.Path & "\" & "DwgParamBatchResult_" & strTimeStamp & ".txt"
    Set objFile = CATIA.FileSystem.CreateFile(strOutputFilePath, True)
    Set objTextStream = objFile.OpenAsTextStream("ForWriting")
    objTextStream.Write strOutput

End Sub

Function GetParameterValue(ByRef iParams As Parameters, ByVal iParamName As String) As String

    Dim objParam As Parameter

    'Try to find the parameter and trap error in case it doesn't exist
    On Error Resume Next
    Set objParam = iParams.Item(iParamName)
    If Err.Number = 0 Then
        GetParameterValue = objParam.ValueAsString
        GetParameterValue = "Not Found"
    End If

End Function

Before running a macro in batch mode

I want to point out that you should always test your script in interactive mode first before running it in batch mode.  As I mentioned earlier, you will not see messages or receive any feedback from the run unless your code outputs any error information to a text file or the command window.  So for our scenario, a dozen or so files were placed in a folder and the script was run to make sure it works properly before moving on to the batch.

How to start the batch

There are quite a few ways to start CATIA in batch mode.  The CATIA help documentation explains five different ways, but I recommend option #4 with the command string in a .bat file.  There are several reasons I tend to do this.  The main reason is that I don’t care much for typing in a big long string at a command prompt.  It is too easy to mistype something especially when the command string gets very long like in this case.  I also like to store the exact command line string somewhere for next time and if you are going to do that you might as well just save it in a text file with a .bat extension.    Once you have prepared the .bat file, all you have to do is double click the file and Windows will execute the command as if you had typed it at a command line.

Lets look at what goes into this command string for a couple of common scenarios.  In each case you need to first specify where the CATIA executable is located (CNext.exe).  After that, you specify options by typing dash (-) followed by the name of the option followed by a space then the value for the option.

Example 1: You want to start CATIA with the default environment

CNextPath –macro –batch ScriptPath

Example 2: You want to start CATIA with a custom environment (more common)

CNextPath –direnv EnvFolderPath –env EnvName –batch –macro ScriptPath

CNextPath The full path to the installed location of CNext.exe

–direnv (Option) The folder path where your environment files are located

EnvFolderPath The value of the folder path where your environment files are located

–env (Option) The name of the environment to start

EnvName The name of the environment to start

–batch (Option) CATIA will be started in batch mode.

–macro (Option) CATIA will execute the requested script

ScriptPath The full path to the script you want to run

In most cases you will probably want to start CATIA with the custom environment that is used at your company, so you will use the second example above.  Below is an example command line string (note that you will have to customize it for your own company specific installation).  Save this string in a text file and save it with a .bat extension.  To test it, simply double click on this .bat file and CATIA should start with the options specified and run the script.

“C:\Program Files\Dassault Systemes\B18\intel_a\code\bin\cnext.exe” –direnv E:\CATEnv –env CATIA.V5R18.B18 -macro -batch “C:\Temp\BatchTest\DwgParamBatch.CATScript”

Edit (05OCT10)

I am editing this article to add more details related to setting up the batch. I added this section after reading the comments below and because when I wrote the article, I didn’t actually run the batch. I wrote that part based on the help docs and from memory, but it has been a while since i ran a batch so I thought I should go back and confirm everything.

You can launch a CATIA V5 batch by starting CNEXT.exe directly or you can use the CATSTART.exe process. The command line syntax is slightly different for each method so I have listed some examples for each below.

Using CNEXT.exe

CD /D D:\Program Files\Dassault Systemes\B18\intel_a\code\bin
CNEXT.exe –direnv E:\CATEnv –env CATIA.V5R18.B18 -batch -macro C:\Temp\BatchTest\DwgParamBatch.CATScript

  • On the first line of the batch file, I change directory using the CD command to the bin folder where the CATIA application files are located.
  • The /D option specifies that you want to change the drive as well as the directory. If your install is not on C:\ you should add this option.
  • When using the CD command to change directory you do not need quotes if the path contains spaces.

CD C:\Program Files\Dassault Systemes\B18\intel_a\code\bin
CNEXT.exe –direnv E:\CATEnv –env CATIA.V5R18.B18 -batch -macro “C:\Temp\BatchTest\Dwg Param Batch.CATScript”

  • In this case, the bin folder is on C:\ so I left out the /D option after the CD command
  • In this case, the macro path contains spaces so it must be enclosed in quotes

Using CATSTART.exe

CD C:\Program Files\Dassault Systemes\B18\intel_a\code\bin
CATSTART.exe –direnv E:\CATEnv –env CATIA.V5R18.B18 -object “-batch -macro C:\Temp\BatchTest\DwgParamBatch.CATScript”

  • When using the CATSTART.exe process, you should use the -object option then enclose the -batch -macro options and the macro path all inside quotes
  • It is OK if the macro path has spaces in it because it is already enclosed in quotes.

Other Considerations

If your CATIA environment is setup to work with ENOVIA and you are prompted to login when CATIA starts in interactive mode then you should setup the batch using one of the options listed below.

Option 1: Start the batch using the CNEXT.exe process (not CATSTART.exe)

Option 2: If you want to use CATSTART.exe then you should open CATIA in interactive mode and go to Tools-Options and turn off the login at startup option. If you do not turn this off, CATIA seems to always start CATIA in interactive mode even when the -batch option is specified.

End Edit (05OCT10)

Results and performance comparison

The above script was run on a set of drawings both in batch mode and interactive mode and average time per drawing was calculated for both scenarios.  In interactive mode, the script averaged about 2.6 minutes per drawing.  Most of this is due to the load time to open the drawing then load it all into memory and update the display with all of that information.  The actual task we are automating (reading the parameter values) probably only takes a small fraction of a second but it takes considerable time to load the data in interactive mode.

In batch mode, the average time was reported to be a little over 3 seconds.  According to these numbers, batch mode is about a 50X improvement.  This is an incredible performance gain!  I was very surprised because I have run batches in the past but never went back and ran them again in interactive mode to compare times.  I did not do any time trials of the script in this article myself because I don’t have a large sample of real world drawings all having the required parameters.  I am just sharing the numbers that were reported back to me.


In this article my goal was to expose you to running a script in batch mode.  I think the basic information I provided should be enough to setup most batch scenarios.  Finally, I hope the real world example and the results it produced were interesting to read about and maybe you can benefit from using a batch in the future.

* If you have some experiences with running scripts in batch mode and maybe even have some performance comparison data you would like to share, please post a comment below.  I’d like to hear more real world examples of the actual performance gains you saw when using batch mode.

Where to get more help

You can get more information about batch mode in the CATIA help documentation.  Just go to the Infrastructure chapter and look for the topic called “Starting a Session on Windows”.

Please take a moment to rate this article…Just click the stars up near the title.

  1. x.klein
    September 27, 2010 at 4:12 am


    I was very interesting by this article
    first reason , all your articles are always very good
    second reason, I run many batch on catia data , so I was very exited about the performance boost between interactive and batch mode (At the moment , I have always run batch with Catia Intercative session)

    I have taken a few time to try to use your script and give you a few information about performane (time) in both mode (Interactive / batch)
    I have take a sample of 50 CATDrawing (size 50 Mo)

    1) interactive mode : Start CATIA , Macros / Execute (select your script)
    => 5 minutes to process the data in interactive mode

    2) create a text file with command line
    “C:\Program Files\Dassault Systemes\catiav5\intel_a\code\bin\cnext.exe” -direnv o:\scm\admin\CATEnv -env CATIA5ENV -macro C:\tmp\ReadParam.CATScript
    => this start catia , process each file (similar behaviour as interactive) , also 5 minutes

    3) try to run the script with -batch option
    “C:\Program Files\Dassault Systemes\catiav5\intel_a\code\bin\cnext.exe” -direnv o:\scm\admin\CATEnv -env CATIA5ENV -macro -batch C:\tmp\ReadParam.CATScript
    CNEXT.exe process is active for 2 second , then process is close , no error message
    but I never succeed to get the .txt result file
    I have try with different option
    – ./CATSTART.exe -run
    – with local data / data on network directory
    – with quote “” without …
    => I was not able to use -batch option !

    About batch performances
    1) When there are many large data to process (load large Assembly)
    Size of CATIA Process always increase , CATIA / Document / Close , do not give back all memory
    => for this batch , I have to add ICountNbFileProcess and stop/start Catia avec 200 files (I do not know how to read memory used by the Process)

    2) About Drawing , in you sample case : read Draw Parameter
    Performances really increase when you un-check option : General/ Load Reference Document”
    but in this case this option can be very dangerous if any other batch are running
    So this may be an idea for an other article , Manage Options/CATSettings with Macros ……

  2. Fernando
    September 27, 2010 at 5:12 am

    Hi Mike,

    There are some issues with CATIA running in batch mode, see links bellow. Unfortunately for my case I couldn’t find an easy way to solve my problem (the only idea which came in my mind was to create another vbscript to rerun the bat file….). Its funny its not the case with all scripts, just those who suppose to use graphic memory (its my guess)…I’m not an expert in programming and I would like to know if others had same problem and how did they solve it.



    By the way, I wish that CATIA help documentation to be so easy to understand like in your articles, everything is very clear, even for an non-native english speaker like me.

  3. September 28, 2010 at 8:01 pm

    Great information and comments guys! Give me some time to review these items and I will post some follow up comments soon…

  4. Fernando
    September 29, 2010 at 12:17 am

    I remembered something else when I was running a batch convert….even if I wrote in the CATScript CATIA.Visible = False, with CATIA running in background, it still shows me that small window with loading visualization (in case of CATProducts)…if you put the option “Do not activate default shapes on open” in CATProduct, of course it will give you an “empty” file…so, my question is, can we run script really invisible (batch might be not always enough)?

    • Raphaël
      March 19, 2014 at 3:08 am

      It’s my question also:
      How do you change a setting in the catia option from VBa scripts? (or CATScript in my case)
      Is there a list of settable options? if not, do you have this option in particular?

  5. October 5, 2010 at 9:43 pm

    I edited this article today and added more details about how to setup the bat file and command line options. Hopefully this clears up any issues with the batch not running correctly.

    Fernando – Sorry, but I can’t comment much on the performance issues you mentioned or having to shut down CATIA after processing a certain number of files. I haven’t personally run into these scenarios.

  6. Samuele
    October 16, 2010 at 3:23 am

    Hello there!

    I need an help. I’m an Italian student, and I want to ask you (you are experts in these topics) if it’s possibile built a geometry (curve, spline, surface loft, volume…) with Catia or other CAD sowftware, via batch mode, without any user interface and then export it in a step, igs.. file. For example How can I do to built a macro or scripts that do a lofted surface, and obtain step file of it, all in automatic??

    Thank you

    Best regards

    • October 16, 2010 at 7:10 am

      That should work fine. Start by recording a macro of yourself creating a new part and making the geometry you want manually. While the macro is still being recorded, go to File-SaveAs and change the file type to the one you want and click OK. Finally, close the part then stop the macro recording. Next, play the macro and see if it runs right and produces the data you expect. You might also want to add some loops, etc. depending on your goals. Once you have the macro running correctly, then follow the instructions in this article to set it up as a batch. Good luck!

      • Samuele
        October 20, 2010 at 11:21 am

        Good!! I will try and will tell you if it’s ok! Thank you very much!!

  7. October 19, 2010 at 1:01 pm

    thank you very much nice text

  8. Thiagu
    October 5, 2011 at 12:20 pm

    Is it possible to invoke notepad thourght CATIA macro

    • Fernando
      October 11, 2011 at 10:17 pm


      Yes, it is. I don’t know if Mike have time to answer you, but bellow you can find a solution in a CATScript.

      CATIA.DisplayFileAlerts = False
      s1=”This CATScript will open different Windows 32 native applications”
      s2=”In the Macro parameters window select and write a value according to your needs, press SET button, skip others and hit RUN button”
      s3=”1 to open Windows Explorer”
      s4=”2 to open Notepad”
      s5=”3 to open Calculator”
      s6=”4 to open Write”
      s7=”5 to open Character Map”
      s8=”6 to open MS Paint ”

      MsgBox s1 & vbCrLf & s2 & vbCrLf & vbCrLf & s3 & vbCrLf & s4 & vbCrLf & s5 & vbCrLf & s6 & vbCrLf & s7 & vbCrLf & s8 & vbCrLf

      Sub CATMain(explorer,notepad,calc,write,charmap,mspaint)

      strComputer = “.”
      Set objWMIService = GetObject(“winmgmts:” _
      & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”)
      Set objStartup = objWMIService.Get(“Win32_ProcessStartup”)

      Set objConfig = objStartup.SpawnInstance_
      objConfig.ShowWindow = SHOW_WINDOW

      Dim result
      Dim params()

      If explorer=1 Then
      Set objProcess1 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess1.Create(“explorer.exe”, null, objConfig, intProcessID)
      End If

      If notepad=2 Then
      Set objProcess2 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess2.Create(“Notepad.exe”, null, objConfig, intProcessID)
      End If

      If calc=3 Then
      Set objProcess3 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess3.Create(“calc.exe”, null, objConfig, intProcessID)
      End If

      If write=4 Then
      Set objProcess4 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess4.Create(“write.exe”, null, objConfig, intProcessID)
      End If

      If charmap=5 Then
      Set objProcess5 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess5.Create(“charmap.exe”, null, objConfig, intProcessID)
      End If

      If mspaint=6 Then
      Set objProcess6 = GetObject(“winmgmts:root\cimv2:Win32_Process”)
      errReturn = objProcess6.Create(“mspaint.exe”, null, objConfig, intProcessID)
      End If

      End Sub

  9. kellerman
    November 17, 2011 at 4:08 am

    great job~~

  10. Suresh
    November 30, 2011 at 9:55 am


    I am looking for a macro which can replace the text in drawing sheet

    I am looking for a macro which can replace the text in catia V5-r20 drawing sheet.

    I have prepared an excel sheet with the current text and the new text with which it has to be replaced.

    Could you please help me out.

    Thanks & Regards,
    Suresh Adusumilli
    Mobile:0 9849612036

  11. January 19, 2012 at 6:19 pm

    great article. Any ideas on how to pass arguments?

    In your example…

    “C:\Program Files\Dassault Systemes\B18\intel_a\code\bin\cnext.exe” –direnv E:\CATEnv –env CATIA.V5R18.B18 -macro -batch “C:\Temp\BatchTest\DwgParamBatch.CATScript”

    Would arguments look something like this:

    “C:\Program Files\Dassault Systemes\B18\intel_a\code\bin\cnext.exe” –direnv E:\CATEnv –env CATIA.V5R18.B18 -macro -batch “C:\Temp\BatchTest\DwgParamBatch.CATScript argument1, argument2, argument3”

    I’m working with a CATVBA that has two arguments on the CATMain Sub, but I can’t seem to figure out the syntax for passing arguments from my shortcut text to the subroutine. I know CATVBA syntax is a little different than CATScript (the module name is added), and I can get an argument-less CATVBA to run fine, but once I try to add arguments, it doesn’t work.

    Thanks, -Nick

  12. Harikrishnan
    April 27, 2012 at 5:35 am

    Can anyone help me how to open a catproduct in visualisation mode while running in batch mode and open a catproduct so that cgr files would be generated for the part files?

  13. Rajesh
    November 2, 2012 at 6:13 am

    Hi …sorry for interrpting in between…is it possible to call catvba macro in catscript.

    • November 3, 2012 at 7:56 am

      I haven’t tried that in a batch but otherwise yes I do it all the time. Use the CATIA.SystemService.ExecuteScript() method. The CATIA help docs explain the details.


  14. December 4, 2012 at 4:54 am

    Are you still writing and updating this blog ?

    • December 18, 2012 at 10:09 pm

      No, unfortunately I have had to take time off from it so I haven’t added new content for a while. I would like to get back to it again though because I do really enjoy it. If you subscribe you will get new content when I do start posting again. Thanks.

  15. August 5, 2013 at 2:35 am

    Hi there! Someone in my Myspace group shared this website with us so I came to check it out.

    I’m definitely enjoying the information. I’m bookmarking and will
    be tweeting this to my followers! Outstanding blog and terrific design
    and style.

  16. Vincent
    April 11, 2014 at 8:02 am

    Can anyone tell me how to pass arguments to the script from the command line
    Currently I have “Path2CNEXT -batch -macro Path2Script” I tried looking elsewhere but can’t find anything. I assume there is a fixed syntax to pass arguments, I just don’t know what it is.

  1. No trackbacks yet.

Leave a Reply to Nicholas Pisca Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: