1

I want wo start powershell window from java application with a command. Cmd is blocked by our company policy.

I've tried

new ProcessBuilder("powershell.exe", "start \"servicemix\" powershell -noexit -command \"dir\"").start();

However it does not open new window. The only way i've managed to open powershell window was with

Desktop.getDesktop().open(new File("full/path/to/powershell"));

But i haven't figured out a way how can i automatically run command in that window.

OS: windows

2
  • 1
    Are you certain company policy allows what you want to do? Commented Oct 27, 2021 at 14:40
  • Not sure, however i'm able to execute commands in powershell in background, just can't open powershell window. Commented Oct 27, 2021 at 14:51

1 Answer 1

1

Try the following:

new ProcessBuilder(
  "powershell.exe", 
  "Start-Process powershell.exe '-NoExit \"[Console]::Title = ''servicemix''; Get-ChildItem\"'"
).start();

Your own attempt tried to use the syntax of the cmd.exe-internal start command (which cannot be used from PowerShell except via an explicit call to cmd.exe), whereas PowerShell's start is an alias for its Start-Process, whose syntax differs (and it doesn't support passing a window title, hence the inclusion of [Console]::Title = ... as a command to execute in the new PowerShell session).

Similarly, dir is an alias for PowerShell's Get-ChildItem cmdlet.

Note that I've removed -Command for brevity, because it is the implied parameter when you pass commands to powershell.exe, the Windows PowerShell CLI. Also note that pwsh.exe, the PowerShell (Core) 7+ CLI, now requires use of -Command (or -c, for short) if you pass commands, because it now defaults to -File in the interest of Unix compatibility.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.