java如何调用ps1 shell脚本
时间: 2023-07-05 17:33:17 浏览: 114
在 Java 中,可以使用 `ProcessBuilder` 类来执行命令和脚本。以下是一个示例代码,演示如何调用 PowerShell 脚本(.ps1 文件):
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PowerShellScriptRunner {
public static void main(String[] args) throws IOException {
// PowerShell 脚本文件路径
String scriptPath = "C:\\scripts\\myscript.ps1";
// 构造命令行参数,执行 PowerShell 脚本
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-ExecutionPolicy", "Unrestricted", scriptPath);
Process process = pb.start();
// 读取脚本执行结果输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待脚本执行完成
try {
int exitCode = process.waitFor();
if (exitCode != 0) {
System.err.println("PowerShell script exited with error code " + exitCode);
}
} catch (InterruptedException e) {
System.err.println("PowerShell script execution interrupted: " + e.getMessage());
}
}
}
```
在这个示例中,我们使用`ProcessBuilder` 构造了一个命令行参数数组,以执行 PowerShell 脚本。其中,`-ExecutionPolicy Unrestricted` 参数指定 PowerShell 执行策略,以允许执行脚本文件。
在 `Process` 对象启动后,我们使用 `BufferedReader` 读取脚本的输出,直到脚本执行完成。最后,我们可以检查脚本的退出代码来确定其是否执行成功。
需要注意的是,如果 PowerShell 脚本中有参数,可以在命令行参数数组中添加相应的参数。例如,如果脚本文件 `myscript.ps1` 有一个参数 `arg1`,则可以将命令行参数数组修改为:
```java
String scriptPath = "C:\\scripts\\myscript.ps1";
String arg1 = "hello";
ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-ExecutionPolicy", "Unrestricted", scriptPath, arg1);
```
这样,脚本文件 `myscript.ps1` 在执行时将接收到参数 `"hello"`。