views:

1033

answers:

1

I am having trouble running a Java program with Windows Powershell 2.0. Any help on this would be greatly appreciated. I want the string "Hello World!" to print to the main Powershell console window. Instead, its getting printed to a separate process window that opens then suddenly closes. I don't know exactly how to tell the powershell to redirect the stdout of the spawned java process to the current powershell console. Basically, i want behavior just like what I get when running java under a DOS shell.

My test class is:

class HelloWorldApp { 
    public static void main(String[] args) { 
        System.out.println("Hello World!"); //Display the string. 
    } 
}

My PowerShell 2.0 code is this:

set-item -path Env:CLASSPATH -value C:\Test 
"CLASSPATH = $Env:CLASSPATH" 
[Diagnostics.Process]::Start('java.exe','-classpath $Env:CLASSPATH C:\
Test\HelloWorldApp')

Alternatively, I tried to run it like so, as I would with a regular DOS shell, with the hope that the output shows in the same console :

java.exe -classpath $Env:CLASSPATH C:\Test\HelloWorldApp

It causes an error. I get this error:

PS >C:\Test\Test.ps1 
CLASSPATH = C:\Test 
java.exe : java.lang.NoClassDefFoundError: C:\Test\HelloWorldApp 
At C:\Test\Site.ps1:3 char:5 
+ java <<<<  -classpath $Env:CLASSPATH C:\Test\HelloWorldApp 
+ CategoryInfo : NotSpecified: (java.lang.NoCla...e\HelloWorldApp: 
                               String) [], RemoteException 
+ FullyQualifiedErrorId : NativeCommandError 
Exception in thread "main"

As far as I can tell, my args are correct because here is what the PCEX ( http://pscx.codeplex.com ) echoargs cmdlet tells me:

PS >echoargs java.exe -classpath $Env:CLASSPATH C:\Test\HelloWorldApp 
Arg 0 is <java.exe> 
Arg 1 is <-classpath> 
Arg 2 is <C:\Test> 
Arg 3 is <C:\Test\HelloWorldApp>

Im convinced there is a way to get this to work because this code works:

## Test.ps1
cd C:\PSJustice
java.exe -classpath . HelloWorldApp

Also, this works:

cd C:\
java.exe -classpath C:\Test HelloWorldApp
+1  A: 

I finally figured it out. It was the smallest typo :

cd c:\
set-item -path Env:CLASSPATH -value C:\Test 
"CLASSPATH = $Env:CLASSPATH" 
java.exe -classpath $Env:CLASSPATH HelloWorldApp

When specifying the Class name it cannot include the absolute path prefixing the class name. Oops.

djangofan