2011-11-16 9 views
12

Voglio richiamare il mio script PowerShell da java. Può essere fatto Ho provato con il seguente codice, ma il flusso non si sta chiudendo.Invoca gli script Powershell da Java

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 richiama uno script di PowerShell che esegue la creazione di sessioni remote ed esegue cmdlet?

Abbiamo supporto per invocare script PowerShell in Java?

Chiunque potrebbe aiutarmi per favore su questo.

In attesa di risposte.

Grazie, rammj

+0

State ottenendo un'eccezione? Dovresti avere i tuoi metodi close() in un blocco finally {}. –

+2

Leggi questo primo http://kylecartmell.com/?p=9 – artbristol

risposta

8

Dopo l'avvio del processo (runtime.exec()), aggiungere una riga per chiudere il flusso di input del processo (che JAVA chiama flusso di output !!):

proc.getOutputStream().close(); 
4

Yes we può creare sessioni remote ed eseguire cmdlet usando lo script PowerShell.

Salvare il seguente script di shell di alimentazione per 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 

del codice 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(); 
     } 

Se non si ottiene in uscita, provate questo: powerShellProcess.getErrorStream() invece powerShellProcess.getInputStream(). Mostrerà gli errori.

4

Ora si può fare facilmente con jPowerShell

powerShell = PowerShell.openSession(); 

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

powerShell.close(); 
+0

Non dovresti essere la copia e incolla di risposte a più domande. –

Problemi correlati