Posts Tagged ‘powershell’

Embedding PowerShell 2 in IronPython

January 25, 2011 1 comment

PowerShell 2 makes the process of embedding PowerShell scripts inside other languages quite a bit simpler than in previous versions:

import clr
from System.Management.Automation import PowerShell
with PowerShell.Create() as ps:
   script = ps.AddScript("param([System.String]$pname)\r\nGet-Process -name $pname")
   script.AddParameters({"pname" : "devenv"})
   output = [o.BaseObject for o in script.Invoke()]

# Now you can access the Process object returned from the PS script.
print output[0].VirtualMemorySize64

You should create the PowerShell instance within a “with” block to ensure it is properly disposed after use. To pass parameters into a PS script, you’ll need to make sure the script accepts a few named parameters using the PS param() statement. Then you create a dict() of the name value pairs and add it as the parameters to the script. A Python list comprehension makes quick work of unwrapping the CLR objects from the PS output collection.

Categories: IronPython Tags: ,

Powershell to find the next available port

March 30, 2009 Leave a comment

Every now and then I’m installing service application on a development machine, and I just want to find the next available port that I can use. Here is a handy Powershell script to do that, which can be easily run as part of a deployment script.

param([int]$port = $(throw("Port required.")))
$isInUse = $FALSE
	trap [System.Net.Sockets.SocketException]
		write-host "Unable to open socket on port $port."
		$script:port = $script:port + 1
		$script:isInUse = $TRUE;

	$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $port)
	write-host "Socket opened successfully on port $port."
	$isInUse = $FALSE
return $port

The easiest way to call this is to include it directly in another powershell script, but if you want to save this as a script that you can call from a different script as a cmdlet, you need to execute this command first, which allows execution of unsigned scripts from the local machine.

set-ExecutionPolicy RemoteSigned

After you’re done with your processing, you may want to set this back to the default restricted setting:

set-ExecutionPolicy Restricted