JavaScript

How to Execute a PowerShell Script in Java

How to Execute a PowerShell Script in Java

You might need to restart a Windows service, read system information, manage files, or call an admin-level task that already lives in a PowerShell script. Instead of rewriting everything in Java, wouldn’t it be nice if Java could simply say:
“Hey PowerShell, you take it from here.”

Why Run PowerShell from Java

Java is great for building cross-platform apps, but Windows has its own powerful tools. PowerShell is one of them.

You may want to execute a PowerShell script in Java when:

  • You need to automate Windows tasks
  • You already have useful PowerShell scripts
  • You need admin-level system control
  • You want to avoid rewriting existing scripts in Java
  • You want your Java app to interact with the OS

Instead of reinventing the wheel, you let each tool do what it does best.

How Java Can Run External Commands

Java doesn’t speak PowerShell natively, but it can run system commands. PowerShell is just another program, so Java can launch it like any other process.

The magic tools here are:

  • ProcessBuilder
  • Runtime.exec() (older but still works)

We’ll use ProcessBuilder because it’s cleaner and safer.

A Simple PowerShell Script to Start With

Before jumping into Java, let’s create a small PowerShell script.

Example: hello.ps1

Write-Output "Hello from PowerShell!"

Save this as hello.ps1 somewhere on your system, for example:
C:\scripts\hello.ps1

Now let’s make Java run it.

How to Execute a PowerShell Script in Java

Here’s the simplest working Java example.

Java Code Example:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunPowerShell {
    public static void main(String[] args) {
        try {
            String command = "powershell.exe -ExecutionPolicy Bypass -File C:\\scripts\\hello.ps1";

            Process process = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            process.waitFor();
            System.out.println("Script finished.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When you run this Java program, you should see:

Hello from PowerShell!
Script finished.

Boom. Java just executed PowerShell.

A Better and Safer Way Using ProcessBuilder

Now let’s improve it using ProcessBuilder, which gives you better control and avoids command parsing issues.

Cleaner Java Code with ProcessBuilder:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class RunPowerShellBetter {
    public static void main(String[] args) {
        try {
            ProcessBuilder builder = new ProcessBuilder(
                    "powershell.exe",
                    "-ExecutionPolicy", "Bypass",
                    "-File", "C:\\scripts\\hello.ps1"
            );

            builder.redirectErrorStream(true);
            Process process = builder.start();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            process.waitFor();
            System.out.println("Done!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This version handles arguments safely and avoids issues when paths contain spaces.

Passing Arguments from Java to PowerShell

Now let’s level up.

PowerShell Script with Parameters:

greet.ps1:

param($name)

Write-Output "Hello, $name! Welcome from PowerShell."

Java Code Passing a Parameter:

ProcessBuilder builder = new ProcessBuilder(
    "powershell.exe",
    "-ExecutionPolicy", "Bypass",
    "-File", "C:\\scripts\\greet.ps1",
    "Alex"
);

Output will be:

Hello, Alex! Welcome from PowerShell.

This is extremely useful when your Java app needs to send dynamic values to PowerShell.

Capturing Errors from PowerShell

Let’s be honest: things break. When they do, you’ll want to know why.

Reading Error Output:

builder.redirectErrorStream(true);

This line merges standard output and error output, so you don’t miss any problems.

If something goes wrong in PowerShell, Java will now catch it.

Handling Execution Policy Issue

PowerShell sometimes blocks scripts for security reasons. You may see errors like:

“running scripts is disabled on this system”

To avoid this, we used:

-ExecutionPolicy Bypass

This tells PowerShell:
“Just this once, trust me.”

It doesn’t permanently change system settings, which is good for security.

Running Inline PowerShell Commands from Java

You don’t always need a script file. Sometimes a quick command is enough.

Java Example with Inline PowerShell:

ProcessBuilder builder = new ProcessBuilder(
    "powershell.exe",
    "-Command",
    "Get-Date"
);

This will print the current date and time directly from PowerShell.

Running PowerShell as Administrator from Java

Here’s the tricky part: Java cannot magically elevate permissions by itself.

If your PowerShell script needs admin rights:

  • Run your Java app as administrator
  • Or create a scheduled task with admin rights
  • Or use a service

There is no safe shortcut here, and that’s a good thing.

Common Problems and How to Fix Them

One common issue is using the wrong path. Always use full paths like
C:\\scripts\\file.ps1 instead of relative paths.

Another issue is spaces in paths. Always quote them or pass them as separate arguments in ProcessBuilder.

Also, never ignore error output. It’s your best friend when debugging.

Making It Cross-Platform Friendly

PowerShell Core (now just called PowerShell) runs on Linux and macOS too.

Instead of powershell.exe, you can use:

"pwsh"

This allows your Java app to run PowerShell scripts on non-Windows systems as well. That’s something many articles never mention.

author-avatar

About Rick Bowen (JavaScript)

Hi, I'm Rick! I'm an accomplished Software Engineer with broad and deep expertise in Go JavaScript, TypeScript, Shell (bash/zsh), Git, SQL & NoSQL Databases, Containers + Kubernetes, Distributed Systems, Reliability Engineering, DevOps, Cloud / Network / Application Security, Identity / Access Management, Linux, macOS/Darwin, CI/CD, SaltStack, Terraform, AWS, GCP, Azure, Internet Protocols, and much more.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments