我可以将字符串变量从 eclipse (java) 发送到 powershell 脚本吗

Can i send a string variable from eclipse (java) to a powershell script

我已经使用 能够通过 java 程序 运行 脚本来简单地获取文本输出(它按要求工作)。

  String command = "powershell.exe  \"C:\Users\--\--\script.ps1\" ";
  Process powerShellProcess = Runtime.getRuntime().exec(command);

我正在考虑在 java 中进一步改进我的脚本,以便在多个页面上使用所述脚本,唯一的变化是理想情况下从 eclipse 中的循环传递的地址变量。我的脚本中有 $address 变量。ps1 文件当前在我的 powershell 脚本的顶部声明它 - 理想情况下我希望能够在 eclipse 中声明 $address

这可能吗?或者我需要以其他方式调整脚本。

谢谢

您可以使用 Runtime.exec 设置变量,但您必须在同一命令中执行此操作,否则脚本将丢失上下文,因为它将 运行 在不同的 powershell 中不知道变量。

因此,在一个命令中,您 Set-Variable(或 SET 用于 cmd,或 EXPORT 用于 linux)并调用您的 ps1 脚本(或在我的例子中,echo):

String myvar = "TextTextText";

final Runtime rt = Runtime.getRuntime();
String[] commands = {"powershell.exe", "Set-Variable", "-Name \"myvar\" -Value \""+myvar+"\";", "echo $myvar"};

Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

String s = null;

while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}