gpt4 book ai didi

java - 在 Java 程序中执行 PowerShell 命令

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:29 25 4
gpt4 key购买 nike

我有一个 PowerShell 命令,我需要使用 Java 程序来执行它。有人可以指导我如何执行此操作吗?

我的命令是 Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |选择对象 DisplayName、DisplayVersion、Publisher、InstallDate |
格式表 –AutoSize

最佳答案

你应该像这样写一个java程序,这里是一个基于Nirman的技术博客的例子,基本思路是执行调用PowerShell进程的命令,如下所示:

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.exe your command";
//Getting the version
String command = "powershell.exe $PSVersionTable.PSVersion";
// Executing the command
Process powerShellProcess = Runtime.getRuntime().exec(command);
// Getting the results
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");

}

}

为了执行一个powershell脚本

String command = "powershell.exe  \"C:\\Pathtofile\\script.ps\" ";

关于java - 在 Java 程序中执行 PowerShell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com