PowerShell: Shortening Web Service Type Names with a Hashtable

When you use the New-WebServiceProxy class, you probably have noticed that PowerShell dynamically generates some really ugly type names. For example, if we get a reference to the Bing web service (you’ll need to get an API key first):

$BingSearch = New-WebServiceProxy -Class BingSearch -Uri "http://api.search.live.net/search.wsdl?AppID=$ApiKey"

… and examine the types contained within it:

$BingSearch.GetType().Assembly.GetExportedTypes() | select FullName

… you’ll notice some ridiculously long type names based on your API key, such as:

Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxyXXXXXXXXXXXXXXXXXXXXXXXXXXX.SearchRequest

Whenever you want to instantiate one of these types, do you want to be typing that enormous type name? Probably not — so, what can we do to make this easier? A simple solution here would be to build a hashtable of short type names that map to their long type names. That way, whenever we want to instantiate a type, all we have to remember is our hashtable variable, and the short name of the type we want.

Let’s take a look:

# Create a hashtable to hold our list of TypeName / FullName mappings
$WebServiceTypes = @{}
# Iterate over each type contained in the BingSearch dynamic assembly
foreach ($Type in $BingSearch.GetType().Assembly.GetExportedTypes())
{
    # Add an item to our hashtable with the short type name and full type name
    $WebServiceTypes.Add($Type.Name, $Type.FullName);
}

# Instantiate a SearchRequest (which is really a:
# Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxyXXXXXXXXXXXXXXXXXXXXXXXXXXX.SearchRequest
New-Object $WebServiceTypes.SearchRequest

That’s all for now folks – hope this helps!