Подтвердить что ты не робот

Вызовите скрипты Powershell с Java

Я хочу вызвать мою powershell script из 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 файл powershell script, который выполняет создание удаленного сеанса и выполняет командлеты?

Есть ли у нас поддержка для вызова скриптов powershell в java?

Кто-нибудь мог бы вам помочь в этом.

Ожидает ответа.

Спасибо, rammj

4b9b3361

Ответ 1

После запуска процесса (runtime.exec()) добавьте строку, чтобы закрыть входной поток процесса (который JAVA вызывает выходной поток!!):

 proc.getOutputStream().close();

Ответ 2

Да, мы можем создать удаленный сеанс и выполнить командлеты с помощью powershell script.

Сохраните следующую оболочку Power script для 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(). Он покажет ошибки.

Ответ 3

Теперь вы можете сделать это легко с помощью jPowerShell

powerShell = PowerShell.openSession();

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

powerShell.close();