ProcessBuilder 只是挂起并且没有完成。我看过很多关于这个的文章,但我仍然没有成功解决这个问题。任何人都可以看到这个问题或有建议吗?
我正在尝试执行一个批处理文件,该批处理文件为活动目录上的用户启用邮件。
代码:
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("TEST");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Starting process");
ProcessBuilder pb = new ProcessBuilder(
"cmd.exe",
"/C",
"Y:\\mail-enable-users-groups.bat");
Process process = null;
try
{
process = pb.start();
ProcessOutputThread t = new ProcessOutputThread(process.getInputStream(), new StringBuffer());
t.start();
process.waitFor();
t.interrupt();
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Process ended");
}
});
frame.add(button);
}
private static class ProcessOutputThread extends Thread
{
private StringBuffer m_output;
private InputStream m_inputStream;
public ProcessOutputThread(InputStream inputstream, StringBuffer output)
{
super( "ProcessOutputThread" );
m_inputStream = inputstream;
m_output = output;
}
@Override
public void run() {
byte[] buffer = new byte[ 8192 ];
try {
while( true )
{
int available = m_inputStream.available();
if( available == 0 )
{
try
{
Thread.sleep( 100 );
}
catch( InterruptedException e )
{
break;
}
continue;
}
int len = Math.min( buffer.length, available );
len = m_inputStream.read( buffer, 0, len );
String outString = new String( buffer, 0, len );
m_output.append( outString );
System.out.println(outString);
}
}
catch( IOException e )
{
e.printStackTrace();
}
}
}
批处理文件:
PowerShell.exe -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Get-User -RecipientTypeDetails User -Filter { UserPrincipalName -ne $Null } | Enable-Mailbox
输出:
Y:\>PowerShell.exe -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Get-User -RecipientTypeDetails User -Filter { UserPrincipalName -ne $Null } | Enable-Mailbox