从java中使用命令启动powershell窗口



我想用一个命令从java应用程序启动powershell窗口。Cmd被我们公司的政策阻止。

我试过了

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

但是它不打开新窗口。我打开powershell窗口的唯一方法是使用

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

但是我还没有想出一个方法,我怎么能在那个窗口自动运行命令。

操作系统:windows

尝试如下:

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

你自己的尝试试图使用cmd.exe-internalstart命令的语法(不能从PowerShell中使用,除非通过显式调用cmd.exe),而PowerShell的startStart-Process别名,其语法不同(并且它不支持传递窗口标题,因此包含[Console]::Title = ...作为命令在新的PowerShell会话中执行)。

同样,dir是PowerShell的Get-ChildItemcmdlet的别名。

注意,为了简洁起见,我删除了-Command,因为当您将命令传递给powershell.exe(Windows PowerShell CLI)时,它是隐含的参数。另请注意,pwsh.exe, PowerShell (Core) 7+ CLI,现在要求使用-Command(或简称-c),如果你传递命令,因为它现在默认为-File为了Unix兼容性的利益。

最新更新