Dot Sourcing - Batch File

Hi guys.
So I have a script that has some functions in it. Lets call the script ScriptTest.ps1
Now on the Powershell command line I am calling and using this script thus
. .\ScriptTest.ps1
Then I am running function called ScriptFunc and parameter called ScriptPars
ScriptFunc ScriptPara
This works fine from the Powershell command prompt. Now I have a requirement to execute this from a .BAT file.
If I execute
powershell -noexit -command . .\ScriptTest.ps1 then it loads the script. What I cant seem to do is pass it the Function and Parameter. I have tried
powershell -noexit -command . .\BackupRestoreMigrate.ps1 ScriptFunc ScriptPara and everything in-between.
Can anyone explain how I can get this to run via a batch file?
Many thanks

Hi WallaceTech,
I‘m writing to check if the suggestions were
helpful, if you have any questions, please feel free to let me know.
If you have any
feedback on our support, please click here.
Best Regards,
Anna
TechNet Community Support

Similar Messages

  • Error running batch files from java source file???

    Dear Friends,
    hi,
    this is with response to a doubt i had earlier ,
    i want to run batch files from the java source file ,i tried using this code (here batrun is the batch file name that contains commands to run other java files)
    try
    String [] command = {"c:\\vishal\\finalmain\\batrun"};
    Runtime.getRuntime().exec(command);
    catch(Exception e)
    but i got the following error.
    java.io.IOException: CreateProcess: gnagarrun error= 2
    plz. help me, i tried all combination w/o success,
    in anticipation(if possible give the code after testing)
    Vishal.

    hello there,
    i solved the prob. by using
    cmd /c start filename ,but i need to pass parameters ie
    cmd /c start java "c:/vishal/runfile a b" where a and b are the parameters. but it is not accepting this in Runtime.getRuntime.exec(),
    any solutions ?????????
    regards,
    Vishal

  • Dot source/calling a function with switch from the cmd line

    Hi
    This is driving me crazy and I know its something really obvious.
    If I have an example script like so, called myexample.ps1
    [CmdletBinding()]
    param
    [Parameter(Mandatory=$false, HelpMessage="My Switch")]
    [switch] $Myswitch,
    [Parameter(Mandatory=$false, HelpMessage="Email Address")]
    [string] $email
    Function Main
    [CmdletBinding()]
    param
    [switch] $Myswitch,
    [string] $email
    if ($Myswitch)
    Write-Host "Switch Enabled"
    Write-Host "Email is $email"
    else
    Write-Host "Switch Disabled"
    Write-Host "Email is $email"
    Main -email $email #This is the line that I think is at fault
    I have two issues
    1) How do I correctly write the code so that the script can be called with either or both parameters. The switch ($Myswitch) is the one that is really causing me issues.
    2) Is invoking it the easiest method/best/most common method of calling it via a batch file
    Here's my understanding
    a) I could dot source it (. .\myexample.ps1) to load the functions into the current session, then call the function
    Main -email hello.com -Myswitch
    or
    Main -email hello.com
    b) or I could Invoke it, which I think is my preference as my final goal here is for it to be called via a batch file in a scheduled task
    & 'C:\Users\myusername\Desktop\MyExample.ps1' -email hello -myswitch
    or
    & 'C:\Users\myusername\Desktop\MyExample.ps1' -email hello
    Any push in the right direction will be appreciated :)

    Why the function?  Just call the file.  We don't "Invoke" scripts. Just call the script..
    # MyExample.ps1
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$false, HelpMessage="My Switch")]
    [switch] $Myswitch,
    [Parameter(Mandatory=$false, HelpMessage="Email Address")]
    [string] $email
    if ($Myswitch){
    Write-Host "Switch Enabled"
    Write-Host "Email is $email"
    }else{
    Write-Host "Switch Disabled"
    Write-Host "Email is $email"
    Now jsut call it like a normal script:
    .\MyExample.ps1 -email someemail -MySwitch
    It is as simple as that.
    If it has to be a function as in a library then you must either dot source or create a module.
    ¯\_(ツ)_/¯

  • Calling powershell script from a batch file

    Hello All,
    I have a batch script that calls a powershell script. Before calling the script I set the execution policy to unrestricted, but when it gets to the line that calls the batch script i still get the confirmation in the command window: "Do you want to
    perform this operation" I then have to press Y for the PS script to run and then my batch script finishes.
    Does anyone know the setting I need to change in order to suppress the confirmation?
    Note: this is Windows 8, see code below
    set THIS_DIR=%~dp0
    powershell Set-ExecutionPolicy unrestricted
    powershell %THIS_DIR%MyScript.ps1 "param1"

    I may sound like a jerk but you really want to look at PowerShell.exe /?
    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]
    PowerShell[.exe] -Help | -? | /?
    -PSConsoleFile
        Loads the specified Windows PowerShell console file. To create a console
        file, use Export-Console in Windows PowerShell.
    -Version
        Starts the specified version of Windows PowerShell.
        Enter a version number with the parameter, such as "-version 2.0".
    -NoLogo
        Hides the copyright banner at startup.
    -NoExit
        Does not exit after running startup commands.
    -Sta
        Starts the shell using a single-threaded apartment.
        Single-threaded apartment (STA) is the default.
    -Mta
        Start the shell using a multithreaded apartment.
    -NoProfile
        Does not load the Windows PowerShell profile.
    -NonInteractive
        Does not present an interactive prompt to the user.
    -InputFormat
        Describes the format of data sent to Windows PowerShell. Valid values are
        "Text" (text strings) or "XML" (serialized CLIXML format).
    -OutputFormat
        Determines how output from Windows PowerShell is formatted. Valid values
        are "Text" (text strings) or "XML" (serialized CLIXML format).
    -WindowStyle
        Sets the window style to Normal, Minimized, Maximized or Hidden.
    -EncodedCommand
        Accepts a base-64-encoded string version of a command. Use this parameter
        to submit commands to Windows PowerShell that require complex quotation
        marks or curly braces.
    -File
        Runs the specified script in the local scope ("dot-sourced"), so that the
        functions and variables that the script creates are available in the
        current session. Enter the script file path and any parameters.
        File must be the last parameter in the command, because all characters
        typed after the File parameter name are interpreted
        as the script file path followed by the script parameters.
    -ExecutionPolicy
        Sets the default execution policy for the current session and saves it
        in the $env:PSExecutionPolicyPreference environment variable.
        This parameter does not change the Windows PowerShell execution policy
        that is set in the registry.
    -Command
        Executes the specified commands (and any parameters) as though they were
        typed at the Windows PowerShell command prompt, and then exits, unless
        NoExit is specified. The value of Command can be "-", a string. or a
        script block.
        If the value of Command is "-", the command text is read from standard
        input.
        If the value of Command is a script block, the script block must be enclosed
        in braces ({}). You can specify a script block only when running PowerShell.exe
        in Windows PowerShell. The results of the script block are returned to the
        parent shell as deserialized XML objects, not live objects.
        If the value of Command is a string, Command must be the last parameter
        in the command , because any characters typed after the command are
        interpreted as the command arguments.
        To write a string that runs a Windows PowerShell command, use the format:
            "& {<command>}"
        where the quotation marks indicate a string and the invoke operator (&)
        causes the command to be executed.
    -Help, -?, /?
        Shows this message. If you are typing a PowerShell.exe command in Windows
        PowerShell, prepend the command parameters with a hyphen (-), not a forward
        slash (/). You can use either a hyphen or forward slash in Cmd.exe.
    Hope that helps! Jason

  • PL/SQL w/ Java to run OS batch file crashes Oracle

    I followed instructions from "Ask Tom" on using PL/SQL with Java to execute an OS batch file. For testing purposes, my batch file does nothing more than display the date and time from the OS.
    However, when I run the PL/SQL that executes this simple batch file repeatedly - anywhere from two to four times, the Oracle instance crashes abruptly. Nothing is written to the alert log. No trace files are created.
    Here is a sample session:
    SQL*Plus: Release 9.0.1.3.0 - Production on Wed Mar 24 10:04:26 2004
    (c) Copyright 2001 Oracle Corporation. All rights reserved.
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    SQL> set serveroutput on size 1000000
    SQL> exec dbms_java.set_output(1000000) ;
    PL/SQL procedure successfully completed.
    SQL> begin
    2 rc('c:\dba_tools\jobs\test.cmd') ;
    3 end ;
    4 /
    C:\Ora9ir2\DATABASE>date /t
    Wed 03/24/2004
    C:\Ora9ir2\DATABASE>time /t
    10:05 AM
    PL/SQL procedure successfully completed.
    SQL> begin
    2 rc('c:\dba_tools\jobs\test.cmd') ;
    3 end ;
    4 /
    C:\Ora9ir2\DATABASE>date /t
    Wed 03/24/2004
    C:\Ora9ir2\DATABASE>time /t
    10:06 AM
    PL/SQL procedure successfully completed.
    SQL>
    Shortly after the second "run", Oracle crashed. All I received was the following error message:
    Unhandled exception in oracle.exe (ORAJOX9.DLL): 0xC0000005: Access Violation
    Here is the Java procedure at the heart of my PL/SQL:
    create or replace and compile
    java source named "Util"
    as
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    public static int RunThis(String args)
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    try
    Process p = rt.exec(args);
    int bufSize = 4096;
    BufferedInputStream bis =
    new BufferedInputStream(p.getInputStream(), bufSize);
    int len;
    byte buffer[] = new byte[bufSize];
    // Echo back what the program spit out
    while ((len = bis.read(buffer, 0, bufSize)) != -1)
    System.out.write(buffer, 0, len);
    rc = p.waitFor();
    catch (Exception e)
    e.printStackTrace();
    rc = -1;
    finally
    return rc;
    I am running Oracle 9i rel. 2 installed on my PC under Windows XP Professional (Service Pack 2). My knowledge of Java is next to nothing.
    Can anyone give me an idea(s) as to what might be causing Oracle to crash?
    Thanks.

    Using 9.2.0.4 I made the following adjustments and it seems to run as often as I care to do it:
    Java changes:
    create or replace and compile
    java source named "Util"
    as
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    public static void RunThis(java.lang.String args)
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    try
    Process p = rt.exec(args);
    int bufSize = 4096;
    BufferedInputStream bis =
    new BufferedInputStream(p.getInputStream(), bufSize)
    int len;
    byte buffer[] = new byte[bufSize];
    // Echo back what the program spit out
    while ((len = bis.read(buffer, 0, bufSize)) != -1)
    System.out.write(buffer, 0, len);
    rc = p.waitFor();
    catch (Exception e)
    e.printStackTrace();
    finally
    PL/SQL Wrapper :
    create or replace procedure rc (cmd VARCHAR2) as
    language java name 'Util.RunThis(java.lang.String)';
    Execution:
    begin
    rc('c:\dba_tools\jobs\test.cmd');
    end ;
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:48 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:48 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:49 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:50 AM
    PL/SQL procedure successfully completed.
    SQL>
    The only thing I really changed was the reurn value from the java procedure. If it has a return value then it should be declared as a function, not a procedure. Since you probably (apparently) weren't using the return value I dropped it and made it a procedure.

  • How do I make a batch file if the .class file uses a foreign package?

    I am trying to make an MS-DOS batch file using the bytecode file from the Java source file, called AddFields.java. This program uses the package BreezySwing; which is not standard with the JDK. I had to download it seperately. I will come back to this batch file later.
    But first, in order to prove the concept, I created a Java file called Soap.java in JCreator. It is a very simple GUI program that uses the javax.swing package; which does come with the JDK. The JDK is currently stored in the following directory: C:\Program Files\Java\jdk1.6.0_07. I have the PATH environment variable set to the 'bin' folder of the JDK. I believe that it is important that this variable stay this way because C:\Program Files\Java\jdk1.6.0_07\bin is where the file 'java.exe' and 'javac.exe' are stored. Here is my batch file so far for Soap:
    @echo off
    cd \acorn
    set path=C:\Program Files\Java\jdk1.6.0_07\bin
    set classpath=.
    java Soap
    pause
    Before I ran this file, I compiled Soap.java in my IDE and then ran it successfully. Then I moved the .class file to the directory C:\acorn. I put NOTHING ELSE in this folder. then I told the computer where to find the file 'java.exe' which I know is needed for execution of the .class file. I put the above text in Notepad and then saved it as Soap.bat onto my desktop. When I double click on it, the command prompt comes up in a little green box for a few seconds, and then the GUI opens and says "It Works!". Now that I know the concept of batch files, I tried creating another one that used the BreezySwing package.
    After I installed my JDK, I installed BreezySwing and TerminalIO which are two foreign packages that make building code much easier. I downloaded the .zip file from Lambert and Osborne called BreezySwingAndTerminalIO.zip. I extracted the files to the 'bin' folder of my JDK. Once I did this, and set the PATH environment variable to the 'bin' folder of my JDK, all BreezySwing and TerminalIO programs that I made worked. Now I wanted to make a batch file from the program AddFields.java. It is a GUI program that imports two packages, the traditional GUI javax.swing package and the foreign package BreezySwing. The user enters two numbers in two DoubleField objects and then selects one of four buttons; one for each arithmetic operation (add, subtract, multiply, or divide). Then the program displays the solution in a third DoubleField object. This program both compiles and runs successfully in JCreator. So, next I moved the .class file from the MyProjects folder that JCreator uses to C:\acorn. I put nothing else in this folder. The file Soap.class was still in there, but I did not think it would matter. Then I created the batch file:
    @echo off
    cd \acorn
    set path=C:\Program Files\Java\jdk1.6.0_07\bin
    set classpath=.
    java AddFields
    pause
    As you can see, it is exactly the same as the one for Soap. I made this file in Notepad and called it AddFields.bat. Upon double clicking on the file, I got this error message from command prompt:
    Exception in thread "main" java.lang.NoClassDefFoundError: BreezySwing/GBFrame
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
    4)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    Caused by: java.lang.ClassNotFoundException: BreezySwing.GBFrame
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ... 12 more
    Press any key to continue . . .
    I know that most of this makes no sense; but that it only means that it cannot find the class BreezySwing or GBFrame (which AddFields extends). Notice, however that it does not give an error for javax.swing. If I change the "set path..." command to anything other than the 'bin' folder of my JDK, I get this error:
    'java' is not recognized as an internal or external command,
    operable program or batch file.
    Press any key to continue . . .
    I know this means that the computer cannot find the file 'java.exe' which I believe holds all of the java.x.y.z style packages (native packages); but not BreezySwing or any other foreign packages. Remember, I do not get this error for any of the native Java packages. I decided to compare the java.x.y.z packages with BreezySwing:
    I see that all of the native packages are not actually visible in the JDK's bin folder. I think that they are all stored in one of the .exe files in there because there are no .class files in the JDK's bin folder.
    However, BreezySwing is different, there is no such file called "BreezySwing.exe"; there are just about 20 .class files all with names like "GBFrame.class", and "GBActionListener.class". As a last effort, I moved all of these .class files directly into the bin folder (they were originally in a seperate folder called BreezySwingAndTerminalIO). This did nothing; even with all of the files in the same folder as java.exe.
    So my question is: What do I need to do to get the BreezySwing package recognized on my computer? Is there possibly a download for a file called "BreezySwing.exe" somewhere that would be similar to "java.exe" and contain all of the BreezySwing packages?

    There is a lot of detail in your posts. I won't properly quote everything you put (too laborious). Instead I'll just put your words inside quotes (").
    "..there are some things about the interface that I do not like."
    Like +what?+ This is not a help desk, and I would appreciate you participating in this discussion by providing details of what it is about the 'interface' of webstart that you 'do not like'. They are probably misunderstandings on your part.
    "Some of the .jar files I made were so dangerously corrupt, that I had to restart my computer before I could delete them."
    Corrupt?! I have never once had the Java tools produce a corrupt Jar. OTOH, the 'cannot delete' problem might relate to the JRE gaining a file lock on the archive at run-time. If the file lock persisted after ending the app., it suggests that the JRE was not properly shut down. This is a bug in the code and should be fixed. Deploying as .class files will only 'hide' the problem (from casual inspection - though the Task Manager should show the orphaned 'java' process).
    "I then turned to batch files for their simple structure and portability (I managed to successfully transport a java.util containing batch file from my computer to another). This was what I did:
    - I created a folder called Task
    - Then I copied three things into this folder: 1. The file "java.exe" from my JDK. 2. The program's .class file (Count.class). and 3. The original batch file.
    - Then I moved the folder from a removable disk to the second computer's C drive (C:\Task).
    - Last, I changed the code in the batch file...:"
    That is the +funniest+ thing I've heard on the forums in the last 72 hours. You say that is easy?! Some points.
    - editing batch files is not scalable to 100+ machines, let alone 10000+.
    - The fact that Java worked on the target machine was because it was +already installed.+ Dragging the 'java.exe' onto a Windows PC which has no Java will not magically make it 'Java enabled'.
    And speaking of Java on the client machine. Webstart has in-built mechanisms to ensure that the end user has the minimum required Java version to run the app. - we can also use the [deployJava.js|http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deplToolkit] on the original web page, to check for minimum Java before it puts the link to download/install the app. - if the user does not have the required Java, the script should guide them through installing it.
    Those nice features in deployJava.js are available to applets and apps. launched using webstart, but they are not available for (plain) Jar's or loose class files. So if 'ensuring the user has Java' is one of the requirements for your launch, you are barking up the wrong tree by deploying loose class files.
    Note also that if you abandon webstart, but have your app. set up to work from a Jar, the installation process would be similar to above (though it would not need a .bat file, or editing it). This basic strategy is one way that I provide [Appleteer (as a downloadable ZIP archive)|http://pscode.org/appleteer/#download]. Though I side-step your part 1 by putting the stuff into a Jar with the path Appleteer/ - when the user expands the ZIP, the parts of the app. are already in the Appleteer directory.
    Appleteer is also provided as a webstart launched application (and as an applet). Either of those are 'easier' to use than the downloadable ZIP, but I thought I would provide it in case the end user wants to save it to disk and transport the app. to a machine with no internet connection, but with Java (why they would be testing applets on a PC with no internet connection, I am not sure - but the option is there).
    "I know that .jar and .exe files are out because I always get errors and I do not like their interfaces. "
    What on earth are you talking about? Once the app. is on-screen, the end user would not be able to distinguish between
    1) A Jar launched using a manifest.
    2) A Jar launched using webstart.
    3) Loose class files.
    Your fixation on .bat files sounds much like the adage that 'If the only tool you have is a hammer, every job starts to look like a nail'.
    Get over them, will you? +Using .bat files is not a practical way to provide a Java app. to the end user+ (and launching an app. from a .bat looks quite crappy and 'second hand' to +this+ user).
    Edit 1:
    The instructions for running Appleteer as a Jar are further up the page, in the [Running Appleteer: Application|http://pscode.org/appleteer/#application] section.
    Edited by: AndrewThompson64 on May 19, 2009 12:06 PM

  • How to find out if a script is ran, or dot-sourced?

    This came up in a little thing I was working on... I'd like to be able to detect if a script is being ran "cold", or if it's being dot-sourced. I've had a good search but no luck so far.
    eg, if a script can detect whether it's being ran as
    .\myscript.ps1
    or
    . .\myscript.ps1
    Not looking for a "what are you trying to do, maybe do it this way instead" sorta deal - this is more of a curio, wondering if it can actually be done.
    Anyone?
    A

    Get-PSCallStack is another excellent way to determine this as well and also works great to determine what file a function came from. You can get some great info from it as shown below.
    $ScriptStack = (Get-PSCallStack)
    Write-Verbose ("Is DotSourced? -- {0}" -f ($ScriptStack[1].position.text -match '^\.\s\.')) -Verbose
    Function Foo {
    $FunctionStack = (Get-PSCallStack)
    Write-Verbose "Originating Script for $($FunctionStack[0].Command): $($FunctionStack[0].ScriptName)" -Verbose
    Write-Verbose "Originating Command calling $($FunctionStack[0].Command): $($FunctionStack[1].Command)" -Verbose
    Function Main {
    $FunctionStack = (Get-PSCallStack)
    Write-Verbose "Originating Script for $($FunctionStack[0].Command): $($FunctionStack[0].ScriptName)" -Verbose
    FOO
    Boe Prox
    Blog |
    Twitter
    PoshWSUS |
    PoshPAIG | PoshChat |
    PoshEventUI
    PowerShell Deep Dives Book

  • How to pass arguments to a batch file from java code

    Hi
    I have a batch file (marcxml.bat) which has the following excerpt :
    @echo off
    if x==%1x goto howto
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
    goto end
    I'm calling this batch file from a java code with the following line of code:
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
    so ,that invokes the batch file.Till that point its ok.
    since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
    %1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
    %2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
    %3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
    could someone help me...
    if i include these parameters too along with the above line of code i.e
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
    I get the following error :
    Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
    could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
    Message was edited by:
    justunme1

    1 - create a java class (Executer.java) for example:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Executer {
         public static void main(String[] args) {
              try {
                   for (int i = 0; i < args.length; i++) {
                        System.out.println(args);
                   Class<?> c = Class.forName(args[0]);
                   Class[] argTypes = new Class[] { String[].class };
                   Method main = c.getDeclaredMethod("main", argTypes);
                   // String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
                   //jdk <6
                   String[] mainArgs = new String[args.length - 1];
                   for (int i = 0; i < mainArgs.length; i++) {
                        mainArgs[i] = args[i + 1];
                   main.invoke(null, (Object) mainArgs);
                   // production code should handle these exceptions more gracefully
              } catch (ClassNotFoundException x) {
                   x.printStackTrace();
              } catch (NoSuchMethodException x) {
                   x.printStackTrace();
              } catch (IllegalAccessException x) {
                   x.printStackTrace();
              } catch (InvocationTargetException x) {
                   x.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
    2 - create a .bat file:
    @echo off
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
    Open MS-DOS, and type the following:
    set TARGET_CLASS=MyTargetClass
    set IN_FILE=in.txt
    set OUT_FILE=out.txt
    Then run your .bat file (in the same ms dos window)
    Hope that Helps

  • Batch file extracting all files from nested archives

    I have managed to leverage a powerful
    forfiles command line utility with the mighty
    7z compression program.
    Below is a simple batch file extracting all files from nested archives hidden at any depth inside other archives and/or folders. After the extraction each archive file turns into a folder having the archive file name. If, for example, there was an "outer.rar"
    archive file containing nothing but an "inner.zip" archive with only "afile.txt" inside, "outer.rar" becomes "...\outer.rar\inner.zip\afile.txt" file system path.
    @echo off
    rem extract_nested_archives.bat
    move %1 "%TMP%"\%2
    md %2
    7z x -o%1 -y %TMP%\%2
    del "%TMP%"\%2
    for %%a in (zip rar jar z bz2 gz gzip tgz tar lha iso wim cab rpm deb) do forfiles /P %1 /S /M *.%%a /C "cmd /c if @isdir==FALSE extract_nested_archives.bat @path @file"
    ARCHIVES ARE DELETED DURING THE EXTRACTION! Make a copy before running the script!
    "7z.exe" and "extract_nested_archives.bat" should be in folders available via the %PATH% environment variable.
    The first parameter of extract_nested_archives.bat is the full path name of the archive or folder that should be fully expanded; the second parameter is just the archive or folder name without the path. So you should run "c:\temp\extract_nested_archives.bat
    c:\temp\outer.rar outer.rar" from the command line to completely expand "outer.rar". "c:\temp" must be the current folder.
    Best regards, 0x000000AF

    Incredibly useful!  Thank you so much.  I did make a couple of small changes to make the script a little easier to use from the end-user perspective.
    First - I don't like making the user input the redundant second parameter, so I added this snippet which extracts it from the first parameter.  The first line of the snippet enables delayed expansion so that special characters in our file name don't
    break anything.  The second line pulls the parameter into a variable, and the 3rd line uses delayed expansion on that new variable.  Before implementing delayed expansion I had problems with file paths which included parentheses.
    SetLocal EnableDelayedExpansion
    Set SOURCE=%1
    For %%Z in (!source!) do (
    set FILENAME=%%~nxZ
    set FILENAME=%FILENAME:"=%
    Anyway once that was done, I just used %FILENAME% everywhere in the script instead of
    %2 (making sure to correct quotes as needed)
    This way, to run my script all you need to run is:
    C:\temp\extract_nested_archives.bat C:\temp\Archive.zip
    Second - I didn't want to modify the Windows environment variable.  So I replaced
    7z with "%PROGRAMFILES%\7-zip\7z.exe"
    I also replaced extract_nested_archives.bat with "%~f0" (which represents the full path+filename of the current script).
    Here is my full script now.  Tested on Windows 8 with the 64-bit version of 7-zip installed:
    @echo off
    Setlocal EnableDelayedExpansion
    Set source=%1
    For %%Z in (!source!) do (
    set FILENAME=%%~nxZ
    set FILENAME=%FILENAME:"=%
    move /Y %1 "%TMP%\%FILENAME%"
    md "%FILENAME%"
    "%PROGRAMFILES%\7-zip\7z.exe" x -o%1 -y "%TMP%\%FILENAME%"
    DEL "%TMP%\%FILENAME%"
    for %%a in (zip rar jar z bz2 gz gzip tgz tar lha iso wim cab rpm deb) do (
    forfiles /P %1 /S /M *.%%a /C "cmd /c if @isdir==FALSE "%~f0" @path @file"

  • Problems Force Running a batch file

    Hi There,
    I am trying to force-run a batch file to copy files from a local NBO Appliance to the C:\tmp directory on the user's workstation. The batch file lives at c:\tmp\branding.bat.
    I cant get the batch file to force run. Zen reporting advises that the batch file has distributed and launched successfully, however the files do not copy.
    However, if i click on the icon for the batch file app - the files copy no problem. I have tried running Workstation Associated and (Unrestricted) User Associated as well as Workstation - Force Run as User.
    Path to executable file:
    %*WinSysDir%\cmd.exe
    Parameters:
    /c "c:\tmp\branding.bat"
    Any ideas? The batch file has to refer to the P: drive as the application covers 40 different sites each with their own appliance containing source files.
    Running NBO2 - ZFD 4 Agent 4.0.1.60 - Clientless
    Desktop XP Workstations
    Thanks
    Thax

    Have the app object copy the batch file to the hard drive from the
    server and then run it locally. This should work with a Middle Tier server.
    thax wrote:
    > Hi there,
    >
    > I cant use the actual server name as this is an application which runs
    > through a middle tier server for multiple NBO sites so therefore needs to
    > use the P: reference...
    >
    >>>> kokoo<[email protected]> 9/03/2006 12:37 >>>
    >
    > TRY edit Scrirts:
    > #\\FS_SERVER_name\VOL\BATCH.BAT
    >
    > edit batch file:
    > xcopy "p:\nal\wxp\ZenPolicies\Branding\*.*" "C:\tmp\ZenPolicies\Branding\"
    > /s /v /e /y
    > ==>
    > xcopy p:\nal\wxp\ZenPolicies\Branding\*.* C:\tmp\ZenPolicies\Branding\ /s
    > /v /e /y
    >
    > "thax" <[email protected]>
    > *******:[email protected]...
    > Hi Jeremy,
    >
    > xcopy "p:\nal\wxp\ZenPolicies\Branding\*.*" "C:\tmp\ZenPolicies\Branding\"
    > /s /v /e /y
    > pause
    >
    > Thax
    >
    > >>> Jeremy Mlazovsky<[email protected]> 8/12/2005 00:20
    >
    > Can we see the contents of your batch file?
    >
    > thax wrote:
    > > Hi There,
    > >
    > > I am trying to force-run a batch file to copy files from a local NBO
    > > Appliance to the C:\tmp directory on the user's workstation. The batch
    >
    > > file lives at c:\tmp\branding.bat.
    > >
    > > I cant get the batch file to force run. Zen reporting advises that the
    >
    > > batch file has distributed and launched successfully, however the files
    >
    > > do not copy.
    > >
    > > However, if i click on the icon for the batch file app - the files copy
    >
    > > no problem. I have tried running Workstation Associated and
    > > (Unrestricted) User Associated as well as Workstation - Force Run as
    > User.
    > >
    > >
    > > Path to executable file:
    > >
    > > %*WinSysDir%\cmd.exe
    > >
    > > Parameters:
    > >
    > > /c "c:\tmp\branding.bat"
    > >
    > > Any ideas? The batch file has to refer to the P: drive as the
    > > application covers 40 different sites each with their own appliance
    > > containing source files.
    > >
    > > Running NBO2 - ZFD 4 Agent 4.0.1.60 - Clientless
    > >
    > > Desktop XP Workstations
    > >
    > > Thanks
    > >
    > > Thax
    > >
    >
    >
    Jeremy Mlazovsky
    Senior System Engineer - Enterprise Desktop
    UDit-Central Hardware Systems & Network Storage
    University of Dayton
    http://forge.novell.com/modules/xfmod/project/?udimage
    http://vmpconfig.sourceforge.net/
    http://regeditpe.sourceforge.net

  • Error Happened at RFC Server Cannot Open the Job Batch File.

    We have BW 7.0  and Data services 12.1. We are scheduling a Infopackage in BW that triggers a job in Dataservices server.
    We had checked the connection between Dataservices source system in BW and RFC server on Dataservices side and these connections are good. on the 3rd party sellections tab in infopackage we specify the batch file name that we exported in Dataservices server. When we execute the infopackage we get the following error.
    Error Happened at RFC Server Cannot Open the Job Batch File.
    This error started occuring from yesterday and prior to that it was working fine. We are not understanding what changed in the system to cause this error.
    Can anyone suggest any solutions for the above issue.
    Thanks,
    Naveen.

    I'm not sure what the root cause would be here. Is the file still available ? Did file permissions change ? ...
    But I wanted to point your attention to the fact that in Data Services/Data Integrator XI 3.2 (=12.2) we significantly enhanced the integration with BW. In XI 3.2, the RFC server is now integrated into the Data Services Management Console (so no need to start as a seperate executable) and you can start jobs from BW by just specifting the job's name in the repo (no need anymore to export execution commands to .bat files). So if upgrading to XI 3.2 is an option, things should go much smoother.
    More details on the wiki  : http://wiki.sdn.sap.com/wiki/display/BOBJ/Loading+BW
    Thanks,
    Ben.

  • Pass Passord Variable to a Batch File using Execute Process Task

    I have an FTP batch file that I want to execute using Execute Process Task. The content of the ftp (ftpscript.cmd) is as below:
    open ftpsite
    UserName
    Password
    ASCII
    get file  c:\temp\test.txt
    bye
    Using SSIS Execute process task, I was able to download data. I configured the Execute Process task as follows:
    Executable: ftp.exe
    Arguments: -s:"c:\temp\ftpscript.cmd"
    The above works fine. But the problem is that I don't want to store the password value in the batch file for security/policy reasons. Please, is there a way I can pass the password value to the ftp executable or the batch file at run time?
    I know how to get and store variables in SSIS but I don't know how to pass this kind of variable to the batch file just before execution.
    Any suggestions will be appreciated. Thanks.

    you can dynamically generate the source (CMD) for the FTP and delete after the execution. The password can be stored in a secure database for example, not 100 % secure, but the best you can do.
    Another option I did was an encrypted VBScript (also quite easy to open in plain text to some people).
    Finally it can be a binary e.g. an EXE with the FTP called as process in it.
    Arthur My Blog

  • Using packages breaks batch file

    Hi there, I wonder if anyone can help me here.
    I've been continuing work on somebody else's previous project, and everything is fine except for the batch file used to run the program from non development. I decided to use Eclipse to develop as opposed to the previous JCreator, and Eclipse gave an error unless I used packages, however this breaks the batch file
    Here's the orginal text from the batch file -
    java.exe -Xmx256m -classpath C:\InsTra\JARS\ant.jar;C:\InsTra\JARS\jaxen-core.jar;C:\InsTra\JARS\jaxen-jdom.jar;C:\InsTra\JARS\jdom.jar;C:\InsTra\JARS\saxpath.jar;C:\InsTra\JARS\xalan.jar;C:\InsTra\JARS\xerces.jar;C:\InsTra\JARS\xml-apis.jar;c:\InsTra\code_files InsTra
    The batch file is located in C:\InsTra, the external JARS are in a JARS subfolder, and the java and class files are in Code_files. The main class is InsTra. I get the error NoClassDefFoundError
    I've tried making the last bit Code_files.InsTra in case it needed to reference the package, but I'm new to this I'm afraid so have little experience of this sort of thing.
    Any help is welcome
    Thanks
    Daniel

    Then either your compiled class is not on the classpath, or you have not used the correct class name. Or both.
    The classpath must point to the root of the package hierarchy.
    The class name must include the package name (which is dictated by the package line at the top of your source file).
    The compiled class file must be in the correct directory.
    Given the information that you have provided, your class file should have the following path:
    c:\InsTra\code_files\Code_files\It should also have the following line at the top of the .java file:
    pacakge Code_files;Class names are case sensitive. Remember that the class path points to the root of the package hierarchy, NOT each of the directories containing class files. For example, if your classpath is thus:
    c:\fooYour class file is in:
    c:\foo\foo\Spong.classWith a package of:
    package foo;And you execute it with:
    java -classpath c:\foo foo.SpongThen it will work. The following will not:
    java -classpath c:\ foo.Spong
    java -classpath c:\foo\foo Spong
    java -classpath c:\foo\foo foo.Spong
    java -classpath c:\foo\foo Spong.class
    etc.

  • Remove odbc system dsn using batch file and odbcconf

    I create user system dsn entries by using a batch file and odbcconf call.  I've found references here on how to do that, yet cannot seem to find any results on how to remove them using that same call.  The library information (http://msdn.microsoft.com/en-us/library/ee388579(VS.85).aspx) states add and modify a system dsn for configdsn and configsysdsn and references equivalent to SQLConfgDataSource function. (http://msdn.microsoft.com/en-us/library/ms716476(VS.85).aspx) but the config data source function has a a removal and this doesn't seem too. 
    Apologies for being obtuse, but I can't seem to locate it.  Any links to how this is done from a batch file are much appreciated.
    Regards,
    NR.

    John C is basically correct, you can remove a System ODBC data source via the registry, but there is apparently no way via odbcconf.exe.  That is of course really stupid and poor programming!
    John, however, forgot another important registry entry.  That key deletion he mentioned will disable the odbc connection, but not remove it entirely.  If you just do that and then open the "ODBC Data Source Administrator", you will find the
    connection is still listed, but you can't remove it or modify it.  It becomes completely screwed up! There is a value to delete as well which dictates if the connection is listed.  Consider it the "header" to the data source.
    Also, in Windows 2003 and 2008 at least, the registry key John C listed is not quite the location to modify either.  This is where to find them in those OSs:
    HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\%DSN%
    or
    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\%DSN%
    The "header" I reffered to is a string value in inside a key (not the whole key!)
    HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources
    or
    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\ODBC Data Sources
    The string value is the data source name.  This entry must be removed to remove the data source listing entirely.
    Here are some batch snipets for creating and then removing an odbc data source.  I'm leaving out some premiliary chunks, but you can figure it out from here. If you can't, you probably shouldn't be messing with this stuff in the first place!
    In these scripts, I create and remove a 32-bit data source in either a 32-bit or 64-bit version of windows.  The windows folder variable gets set to either "C:\Windows\System32" or "C:\Windows\SysWOW64" depending on the os.  In case you didn't
    know, on a 64-bit machine there is are also 2 differrent versions of the "ODBC Data Source Administrator" gui tool and the data source lists differ (32-bit vs 64-bit lists).  The 32-bit version on a 64 bit OS is found at "C:\Windows\SysWOW64\odbcad32.exe". 
    The one in the start menu will load the 64-bit version so you will never find your 32-bit connections there.
    Note - for simplicity I use the database name as the user name and and the data source name as well (in case there was any confusion). 
    Create the connection like so:
    echo Creating 32-Bit System ODBC Connection "%DatabaseName%"...
    "!WindowsFolder!\ODBCCONF.EXE" CONFIGSYSDSN "!ODBCDriver!" "DSN=%DatabaseName%;Server=localhost;Port=3306;Database=%DatabaseName%;UID=%DatabaseName%;PWD=%DatabasePassword%"
    And then remove it like this:
    echo Removing 32-Bit System ODBC Connection "%DatabaseName%"...
    if "%WindowsBits%"=="32" (
    If Exist "!TempRegFile!" Del "!TempRegFile!"
    echo Windows Registry Editor Version 5.00>>"!TempRegFile!"
    echo.>>"!TempRegFile!"
    echo [-HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\%DatabaseName%]>>"!TempRegFile!"
    echo [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources]>>"!TempRegFile!"
    echo "%DatabaseName%"=->>"!TempRegFile!"
    regedit /s "!TempRegFile!"
    ) else (
    If Exist "!TempRegFile!" Del "!TempRegFile!"
    echo Windows Registry Editor Version 5.00>>"!TempRegFile!"
    echo.>>"!TempRegFile!"
    echo [-HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\%DatabaseName%]>>"!TempRegFile!"
    echo [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\ODBC Data Sources]>>"!TempRegFile!"
    echo "%DatabaseName%"=->>"!TempRegFile!"
    regedit /s "!TempRegFile!"
    If Exist "!TempRegFile!" Del "!TempRegFile!"

  • DSC powershell xwindowsprocess to execute batch file under different user account

    DSC powershell run under "NT AUTHORITY\SYSTEM".
    I am trying to execute a batch file under different user account using xwindowsprocess in DSC resource kit.
    I created a custom dsc resource with 3 parameters namely Exepath, Arguments, Credential.
    I received those parameter values in settargetresource method.
    CallPInvoke
    [Source.NativeMethods]::CreateProcessAsUser(("$ExePath "+$Arguments), $Credential.GetNetworkCredential().Domain, $Credential.GetNetworkCredential().UserName, $Credential.GetNetworkCredential().Password)
    I tested it by invoking a batch file and writing username under which it executes to a text file.
    After executing, the output text file still contains the "Systemname$".

    Configuration Sample_xService_ServiceWithCredential
    param
    [string[]]
    $nodeName = 'localhost',
    [System.String]
    $Name,
    [System.String]
    [ValidateSet("Automatic", "Manual", "Disabled")]
    $StartupType="Automatic",
    [System.String]
    [ValidateSet("LocalSystem", "LocalService", "NetworkService")]
    $BuiltInAccount="LocalSystem",
    [System.Management.Automation.PSCredential]
    $Credential,
    [System.String]
    [ValidateSet("Running", "Stopped")]
    $State="Running",
    [System.String]
    [ValidateSet("Present", "Absent")]
    $Ensure="Present",
    [System.String]
    $Path,
    [System.String]
    $DisplayName,
    [System.String]
    $Description,
    [System.String[]]
    $Dependencies
    Import-DscResource -Name MSFT_xServiceResource -ModuleName xPSDesiredStateConfiguration
    Node $nodeName
    xService service
    Name = $Name
    DisplayName = $DisplayName
    Ensure = $Ensure
    Path = $Path
    StartupType = $StartupType
    Credential = $credential
    $Config = @{
    Allnodes = @(
    Nodename = "localhost"
    PSDSCAllowPlainTextPassword = $true
    #Sample Scenarios
    $credential = Get-Credential
    Sample_xService_ServiceWithCredential -ConfigurationData $Config -Name "Sample Service" -DisplayName "Sample Display Name" -Ensure "Present" -Path "C:\DSC\TestService.exe" -StartupType Automatic -Credential $credential
    ¯\_(ツ)_/¯

Maybe you are looking for

  • Going to the Bar for a friend = issue?

    Hi all, My friend's has been experiencing issues with their MagSafe adapter (burned, frayed wire). However, my friend is physically unable to go to the local Apple Store/Genius Bar themselves, so I offered to take it to Apple for them, since it is ne

  • Child Records

    Hi, I have master and child block. Join column is Header id. I want to enforce the user to enter atleast one record in the child block before saving the header record. How to do this. Regards/Prasanth

  • Wildcards in Variables

    Can wildards be put in variables? I have used * and % in the equation below and i cannot get the result i am after. Here is the formula =If <Location Name>= "B03*" Then "B03" basically i am trying to say anything that begins with B03 classify it as B

  • Transfer photos from Mac notebook to iMac

    Best way to transfer Photos from Mac notebook to my imac

  • Update rules/communication strucuture clarifications

    Hello EVerybody I am really getting confused in figuring out whats finally coming to the data-target or in general mappings. I have a single ods that has 4 update rules from 4 distinct infosources. q1. what is in my communication stucture ( does it c