Home > Back-end >  Starting powershell window with a command from java
Starting powershell window with a command from java

Time:10-28

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

CodePudding user response:

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.

  • Related