Search code examples
javapowershelluser-inputprompt

How to pass user inputs for a java program in powershell script


I have a java program abc.java which prompts the user for some input. Now I am calling this java file in my powershell script. When I am executing the powershell, it comes to the prompt for the input. So now how can I enter the user input here?

My powershell script is as follows:

cd 'C:\LDAP\test1'
java abc

The output of the above run is as follows:

PS C:\> C:\LDAP\sample.ps1
Enter the prefix:

Now how to enter the value? I am ok with either entering the input during the runtime or even hardcode the input in the powershell script.

System.out.println("Enter the prefix:"); 

String strPrefix = objScanner.nextLine(); 

System.out.println("Enter the Country:"); 

String strLocation = objScanner.nextLine();

Solution

  • I wrote abc.java like this.

    import java.util.Scanner;        
    
    class abc {
        public static void main(String[] args) {
            try {
                Scanner objScanner = new Scanner(System.in);
                System.out.print("Enter the prefix:"); 
                String strPrefix = objScanner.nextLine(); 
                System.out.println("Prefix is \"" + strPrefix + "\"");
    
                System.out.print("Enter the Country:"); 
                String strLocation = objScanner.nextLine();
                System.out.println("Country is \"" + strLocation + "\"");
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    And my powershell seems as follows.

    PS C:\> C:\LDAP\sample.ps1
    Enter the prefix:Mr
    Prefix is "Mr"
    Enter the Country:America
    Country is "America"
    

    If you use

    System.out.println("Enter the prefix:"); 
    

    and

    System.out.println("Enter the Country:"); 
    

    ,powershell seems as follows.

    PS C:\> C:\LDAP\sample.ps1
    Enter the prefix:
    Mr
    Prefix is "Mr"
    Enter the Country:
    America
    Country is "America"