【问题标题】:Invoke Powershell scripts from Java从 Java 调用 Powershell 脚本
【发布时间】:2011-11-16 06:31:10
【问题描述】:

我想从 java 调用我的 powershell 脚本。能不能做到。我尝试使用以下代码,但流没有关闭。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TestPowershell {

    public static void main(String[] args) throws IOException 
    {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("powershell C:\\testscript.ps1");
        InputStream is = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isr);
        String line;
        while ((line = reader.readLine()) != null)
        {
            System.out.println(line);
        }
        reader.close();
        proc.getOutputStream().close();
    }

}

java 是否调用执行创建远程会话并执行 cmdlet 的 powershell 脚本?

我们是否支持在 java 中调用 powershell 脚本?

谁能帮忙解决这个问题。

等待您的回复。

谢谢, rammj

【问题讨论】:

  • 您遇到异常了吗?您应该将 close() 方法放在 finally{} 块中。
  • 先阅读本文kylecartmell.com/?p=9

标签: java powershell


【解决方案1】:

启动进程后(runtime.exec()),添加一行关闭进程的输入流(JAVA称之为输出流!!):

 proc.getOutputStream().close();

【讨论】:

    【解决方案2】:

    现在您可以使用 jPowerShell 轻松做到这一点

    powerShell = PowerShell.openSession();
    
    //Print results    
    System.out.println(powerShell.executeScript("\"C:\\testscript.ps1\"").getCommandOutput());
    
    powerShell.close();
    

    【讨论】:

    • 你不应该复制和粘贴多个问题的答案。
    【解决方案3】:

    是的,我们可以使用 powershell 脚本创建远程会话并执行 cmdlet。

    将以下 Power shell 脚本保存到 testscript.ps1

     #Constant Variables
    $Office365AdminUsername="YOUR_USERNAME"
    $Office365AdminPassword="TOUR_PASSWORD"
    
    #Main
    Function Main {
    #Remove all existing Powershell sessions
        Get-PSSession | Remove-PSSession
    
    #Encrypt password for transmission to Office365
        $SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365AdminPassword -Force
    
    
    #Build credentials object
        $Office365Credentials  = New-Object System.Management.Automation.PSCredential $Office365AdminUsername, $SecureOffice365Password 
    Write-Host : "Credentials object created"
    
    #Create remote Powershell session
        $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Office365credentials -Authentication Basic –AllowRedirection  
    Write-Host : "Remote session established"
    
    #Check for errors
    if ($Session -eq $null){
        Write-Host : "Invalid creditials"
    }else{
        Write-Host : "Login success"
        #Import the session
            Import-PSSession $Session
    }
    
    #To check folder size
    Get-MailboxFolderStatistics "YOUR_USER_NAME"  | Select Identity, FolderAndSubfolderSize
    
    exit
    }
    
    # Start script
    . Main  
    

    Java 代码:

    try {
                String command = "powershell.exe \"C:\\testscript.ps1\"";
                ExecuteWatchdog watchdog = new ExecuteWatchdog(20000);
                Process powerShellProcess = Runtime.getRuntime().exec(command);
                if (watchdog != null) {
                    watchdog.start(powerShellProcess);
                }
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
                String line;
                System.out.println("Output :");
                while ((line = stdInput.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    如果你没有得到输出,试试这个:powerShellProcess.getErrorStream() 而不是powerShellProcess.getInputStream()。它会显示错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-07
      • 2016-06-22
      • 2011-10-17
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多