java - 通过Java远程运行Powershell脚本

标签 java powershell command invoke-command

我能够通过 Powershell 本身运行以下 powershell 命令,

invoke-command -ComputerName "compName" -filepath "c:\script.ps1" -credential "admin"

但是当我尝试通过 Java 运行它时,出现错误。听起来“Invoke-command”不被识别为通过 Java 运行的程序。如果是这种情况,还有其他解决办法吗?

Process p = new ProcessBuilder()
                .inheritIO()
                .command("invoke-command", "-computername", "compName",
                        "-filepath", "C:\\script.ps1").start();

错误,

Cannot run program "invoke-command": CreateProcess error=2, The system cannot find the file specified

附注该错误与提供的 filePath 无关,而是与调用命令本身相关。

谢谢。

最佳答案

正如您所写的invoke-command是一个Powershell命令,因此您必须调用Powershell来运行命令,如下所示:

Process p = new ProcessBuilder()
                .inheritIO()
                .command("powershell", "invoke-command", "-computername", "compName",
                        "-filepath", "C:\\script.ps1").start();

关于java - 通过Java远程运行Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40351357/

相关文章:

powershell - 如何从适用于 PowerShell 的 AzureAD v2 cmdlet 访问新创建的应用程序的 ObjectId?

powershell - 安装模块 : The term 'Install-Module' is not recognized as the name of a cmdlet

ruby-on-rails - 使用加载命令在 Rails 控制台中调用脚本时传递参数

Java - apache commons exec,在同一个 "context"中运行2个命令

java - 错误 : Could not find or load main class

Java ASM - 如何在方法中创建局部变量

powershell - 如何在 PowerShell 中通过管道传输二进制数据

java - 如何使用 Selenium 获取在路由到另一个 url 之前临时出现的重定向 url?

java - Eclipse中导入类的问题

java - 将 long 值从 java Date.getTime() 转换为 VB.Net 中的 DateTime