我正在移植一个利用 3rd 方模块 (NetCmdlets) 的 PS4 脚本,并且在 Powershell 窗口中工作得非常好,但似乎在从 Java 程序运行时忘记了如何加载 3rd 方模块。
我会对任何人对此的潜在原因和解决方案的想法感兴趣......
这是调用 Java PGM:
package ImagineOne.PSJava2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteCommand {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// This is the command
// String command = "powershell.exe $PSVersionTable.PSVersion | Get-Member";
// String command = "powershell.exe C:\\Users\\versaggi\\Desktop\\PowerCLI\\DevScripts\\CANES_VMWare_Extraction_Functions.ps1";
String command = "powershell.exe C:\\Users\\versaggi\\Desktop\\PowerCLI\\DevScripts\\CANES_IBM_RackSwitch_Extraction_Functions.ps1";
Process powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
stdout.close();
System.out.println("Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream()));
while ((line = stderr.readLine()) != null) {
System.out.println(line);
}
stderr.close();
System.out.println("Done");
}
} //End Class
这是输出:
Output:
** NetCmdlets Modules Loaded **
** Disconnected from RackSwitch **
Error:
Import-Module : **The specified module 'C:\Windows\System32\WindowsPowerShell\v1.
0\Modules\NetCmdlets\NetCmdlets.psd1' was not loaded because no valid module
file was found in any module directory**.At C:\Users\versaggi\Desktop\PowerCLI\De
vScripts\CANES_IBM_RackSwitch_Extraction_Functions.ps1:732 char:1
+ Import-Module
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\NetCmdlets\NetC ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : ResourceUnavailable: (C:\Windows\Syst...NetCmdle
ts.psd1:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm
ands.ImportModuleCommand
Done
这是 PowerShell 脚本:(它只应该加载模块作为测试 [概念证明])
Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\NetCmdlets\NetCmdlets.psd1
write-host "** NetCmdlets Modules Loaded ** "
我仔细阅读过的一些研发考虑:
http://technirman.blogspot.com/2014/06/invoke-powershell-commands-through-java.html