Search code examples
javapowercli

Invoke powershell script from java


I am trying to invoke some powercli script from Java and it fails.

I am working with VMWare esx

This is my Java code:

String command = "cmd.exe C:\\Users\\mayan\\Desktop\\scriptPS.ps1";
Process powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();

This is my script (.ps1 file):

C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1
Get-VM -Name dev-maya | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$false           
Get-VM -Name dev-maya | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$true

Java invoke the first command and ignore the rest.

Does anyone have idea how to fix this problem?


Solution

  • Try replacing

    C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1
    

    with

    Add-PSSnapin vmware.vimautomation.core
    

    You'll also need to run connect-viserver as implied in the other answer.