2011-11-16 109 views
12

Deseo invocar mi script de powershell desde java. Se puede hacer. Intenté con el siguiente código, pero la transmisión no se está cerrando.Invocar scripts de Powershell de 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(); 
    } 

} 

¿Invoca Java un script de powershell que realiza la creación de una sesión remota y ejecuta cmdlets?

¿Tenemos soporte para invocar scripts de powershell en java?

Cualquiera podría ayudarme con esto.

En espera de sus respuestas.

Gracias, rammj

+0

¿Está recibiendo una excepción? Debería tener sus métodos close() en un bloque finally {}. –

+2

Lea esto primero http://kylecartmell.com/?p=9 – artbristol

Respuesta

8

Después de iniciar el proceso (runtime.exec()), añadir una línea para cerrar el flujo de entrada del proceso (que Java llama flujo de salida !!):

proc.getOutputStream().close(); 
4

Sí se puede crear sesiones remotas y ejecutar cmdlets usando script de powershell.

Guarde la siguiente secuencia de comandos shell de encendido para 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 

Código 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(); 
     } 

Si usted no recibe la salida, intente esto: powerShellProcess.getErrorStream() lugar powerShellProcess.getInputStream(). Mostrará los errores.

4

Ahora puede hacerlo fácilmente con jPowerShell

powerShell = PowerShell.openSession(); 

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

powerShell.close(); 
+0

No debe copiar y pegar respuestas a varias preguntas. –

Cuestiones relacionadas