【问题标题】:Starting powershell window with a command from java使用来自 java 的命令启动 powershell 窗口
【发布时间】:2021-10-27 14:26:42
【问题描述】:

我想使用命令从 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

【问题讨论】:

  • 你确定公司政策允许你想做什么?
  • 不确定,但是我可以在后台在powershell中执行命令,只是无法打开powershell窗口。

标签: java windows powershell


【解决方案1】:

尝试以下方法:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2023-03-29
    • 2018-08-18
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多