我有一个PowerShell Command,我需要使用Java程序执行。有人能教我怎么做吗?我的命令是Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
PowerShell Command
Java
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize
ljo96ir51#
你应该写一个这样的java程序,这里有一个基于Nirman的Tech Blog的示例,基本思想是像这样执行调用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\" ";
3bygqnnd2#
不需要重新发明轮子。现在你可以使用jPowerShell。(披露:我是这个工具的作者)。
String command = "Get-ItemProperty " + "HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* " + "| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate " + "| Format-Table –AutoSize"; System.out.println(PowerShell.executeSingleCommand(command).getCommandOutput());
wr98u20j3#
你可以尝试调用powershell.exe与一些命令,如:
String[] commandList = {"powershell.exe", "-Command", "dir"}; ProcessBuilder pb = new ProcessBuilder(commandList); Process p = pb.start();
35g0bw714#
您可以在命令中使用-ExecutionPolicy RemoteSigned。String cmd =“cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive C:\Users\File.ps1
4条答案
按热度按时间ljo96ir51#
你应该写一个这样的java程序,这里有一个基于Nirman的Tech Blog的示例,基本思想是像这样执行调用PowerShell进程的命令:
为了执行powershell脚本
3bygqnnd2#
不需要重新发明轮子。现在你可以使用jPowerShell。(披露:我是这个工具的作者)。
wr98u20j3#
你可以尝试调用powershell.exe与一些命令,如:
35g0bw714#
您可以在命令中使用-ExecutionPolicy RemoteSigned。
String cmd =“cmd /c powershell -ExecutionPolicy RemoteSigned -noprofile -noninteractive C:\Users\File.ps1