从Java运行PowerShell文件表示该文件没有';。ps1和x27;延伸
我正试图找出如何从Java中运行PowerShell脚本。请记住,我对Java非常陌生,所以可能有更好的方法 目前我在Fedora 25工作站上安装了PowerShell 如前所述,首先安装Fedora.NET核心包:从Java运行PowerShell文件表示该文件没有';。ps1和x27;延伸,java,bash,powershell,fedora,Java,Bash,Powershell,Fedora,我正试图找出如何从Java中运行PowerShell脚本。请记住,我对Java非常陌生,所以可能有更好的方法 目前我在Fedora 25工作站上安装了PowerShell 如前所述,首先安装Fedora.NET核心包: sudo dnf config-manager --add-repo https://copr.fedorainfracloud.org/coprs/nmilosev/dotnet-sig/repo/fedora-25/nmilosev-dotnet-sig-fedora-25.
sudo dnf config-manager --add-repo https://copr.fedorainfracloud.org/coprs/nmilosev/dotnet-sig/repo/fedora-25/nmilosev-dotnet-sig-fedora-25.repo
sudo dnf update
sudo dnf install dotnetcore
然后下载并安装
sudo dnf install Downloads/powershell-6.0.0_beta.1-1.el7.centos.x86_64.rpm
powershell
然后,我使用本文中的代码运行“Hello world”ps1文件:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PowerShellCommand {
public static void main(String[] args) throws IOException {
String command = "powershell $PSVersionTable.PSVersion";
command = "powershell -ExecutionPolicy RemoteSigned -NoProfile -NonInteractive -File \"/home/b/Downloads/MyScript.ps1\"";
Process powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();
String line;
System.out.println("Standard Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
powerShellProcess.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Standard Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
powerShellProcess.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
}
尝试运行.ps1文件时出现的错误是:
处理-文件“/home/b/Downloads/MyScript.ps1”失败,因为
文件没有扩展名“.ps1”。指定一个有效的窗口
PowerShell脚本文件名,然后重试
当尝试在Java代码中运行此命令时,我确实获得了变量的正确输出:
String command = "powershell $PSVersionTable.PSVersion";
在Gnome终端中,从bash shell运行以下命令时,该命令也可以正常工作,并且脚本可以通过说“Hello world”来正确执行:
谢谢您的帮助。注意:
- 自问题发布以来,PowerShell核心可执行文件的名称已从
更改为PowerShell
,这反映在下面的解决方案中pwsh
- 问题中的特定脚本文件路径-
-并不严格要求引用(包含在/home/b/Downloads/MyScript.ps1
)中),但一般健壮的解决方案应该使用引用——这是下面演示的内容“…”
通过将命令构造为单个字符串,嵌入的
“
实例将保留为文本,这就是错误消息反映的内容:
处理-文件“/home/b/Downloads/MyScript.ps1”
请注意,“…”
中引用的值如何包含封闭的“…”
-以及字面上包含“
字符的路径显然不存在,并且由于以“
”结尾,因此没有.ps1
扩展名。所做的是通过对字符串进行仅空格的标记化来执行。因此,生成的数组保留嵌入的引号,并且也不会将带有嵌入空格的带引号的标记识别为单个标记
要解决此问题,您有两个选择:
- (a) 使用
和-Command
而不是&
来调用脚本,在这种情况下,PowerShell采用另一轮解析,因此嵌入式-File
实例被识别为具有语法功能“
String command = "pwsh -NoProfile -Command & \"/home/b/Downloads/MyScript.ps1\"";
- (b) 最好将命令行的标记作为字符串数组传递:
String[] command = new String[] { "pwsh", "-NoProfile", "-File", "/home/b/Downloads/MyScript.ps1" };
-File
参数,所有传递的参数都被视为文本
String[] command = new String[] { "pwsh", "-NoProfile", "-File", "/home/b/Downloads/MyScript.ps1" };