1

When we run commands on power cli it displays the operations we have performed.
For example

Start-VM –VM “VM1”  

simply starts the VM in the v center.

I want to write such code in Python that we can call these commands in code and store the output and display to the user.
Is there any way to link our Python code with power cli commands or we can say can we bind power cli code inside Python?

Sebastian Kreft
  • 7,819
  • 3
  • 24
  • 41

1 Answers1

0

You want two things: dot source the script (which is (as far as I know) similar to python's import), and subprocess.call.

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&hello"])

So what happens here is that we start up powershell, tell it to import your script, and use a semicolon to end that statement. Then we can execute more commands, namely, hello.

You also want to add parameters to the functions, so let's use the one from the article above (modified slightly):

Function addOne($intIN)
{
Write-Host ($intIN + 1)
}

and then call the function with whatever parameter you want, as long as powershell can handle that input. So we'll modify the above python to:

import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePowershell\";", "&addOne(10)"])

this gives me the output:

PowerShell sample says hello.
11

You'll need to edit the above to include the PowerCLI library, but it should work.

solar411
  • 832
  • 1
  • 12
  • 35