In this exercise, we'll use IronPython to create a PowerShell runspace and execute a simple PowerShell command. This exercise is intended to illustrate how IronPython can integrate with PowerShell, expanding its capabilities.
- Create a Python file called
powershell.py
in the same folder as your IronPython console. (ex: C:\Program Files\IronPython 3.4) - Start by importing the necessary .NET libraries that allow IronPython to interact with PowerShell.
clr.AddReference('System.Management.Automation')
from System.Management.Automation import PowerShell
- After importing the necessary libraries, create a new instance of PowerShell.
ps = PowerShell.Create()
- Next, add the PowerShell command you wish to execute. In this example, we will use the Get-Process command to retrieve the status of processes on a local or remote computer.
ps.AddScript("Get-Process")
- After adding the command, you can now invoke it and get the output. The results will be printed on the console.
output = ps.Invoke()
print(output)
- Finally, execute the entire IronPython script using your IronPython environment, ipy.exe.
import clr;
clr.AddReference('System.Management.Automation')
from System.Management.Automation import PowerShell
ps = PowerShell.Create()
ps.AddScript("Get-Process")
output = ps.Invoke()
print(output)
- Do this by opening a PowerShell window in the folder. You should see a list of running processes on your machine. If you see the below result, then you have successfully accessed PowerShell runspace using IronPython, however, the information is not in a format that we can read.
.\ipy.exe powershell.py
<System.Collections.ObjectModel.Collection`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]] object at 0x000000000000002B [System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]]>
- To then read the PSObject, we will need to iterate over the object and print it to our console.
import clr;
clr.AddReference('System.Management.Automation')
from System.Management.Automation import PowerShell
ps = PowerShell.Create()
ps.AddScript("Get-Process")
output = ps.Invoke()
for line in output:
print(line)