I want to write a java code which will use powershell command to connect the remote system and execute java -version command in remote system. Can someone please help me on this.
Thanks in advance :)
I want to write a java code which will use powershell command to connect the remote system and execute java -version command in remote system. Can someone please help me on this.
Thanks in advance :)
Have you attempted to use Invoke-Command instead of Enter-PSSession?
After some testing of the PowerShell and tweaking it to get the return values I had to end up with the following code.
$pw = convertto-securestring -AsPlainText -Force -String "Password"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Domain\User",$pw
$session = New-PSSession -ComputerName Computer -Credential $cred
Invoke-Command -Session $session -ScriptBlock { return "$(&java -Xms256m -Xmx256m -version 2>&1)";}
I had to pass memory configuration via Invoke-Command because remote java via WinRM seems to try and fill more memory than is available. I also had to redirect the error output (2>&1) as the return from the -version call is picked up as an Error by PowerShell.
I guess your Java would read something like this:
runtimeProcess = Runtime.getRuntime().exec(new String[] {"powershell.exe", "/c","$pw = convertto-securestring -AsPlainText -Force -String \""+password+"\"; $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist \""+domain+"\\"+user+"\""+",$pw"+ "; $session = new-pssession -computername \""+host+"\" -credential $cred"+ "; Invoke-Command -Session $session -ScriptBlock { return \"$(&java -Xms256m -Xmx256m -version 2>&1)\";}
To Set the Shell Memory:
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 2048
To Set the Shell Memory Remotely once configuring your credentials as above:
Invoke-Command -Session $session -ScriptBlock { Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 2048 }
You could also attempt to run it with a lower -Xmx or -Xms value, though java may fail to load in lower memory environments.
runtimeProcess = Runtime.getRuntime().exec(new String[] {"powershell.exe", "/c","$pw = convertto-securestring -AsPlainText -Force -String \""+password+"\"; $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist \""+domain+"\\"+user+"\""+",$pw"+ "; $session = new-pssession -computername \""+host+"\" -credential $cred"+ "; Invoke-Command -Session $session -ScriptBlock { return \"$(&java -Xms16m -Xmx64m -version 2>&1)\";}
I hope this helps.
Cheers, Chris.
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 or: Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 2048