In the last post we we’re playing around with how to extract a Product Key from an MSDN exported XML document. We’ll take this a step further today and see if we turn it into something a little more useful.
Building on the previous script, we want to list the products that match our search criteria and then select the one we want the Product Key for. As well as displaying this information on screen, it would be useful if the key could be put into the clipboard, ready for use.
[xml]$msdn = Get-Content MSDN-Sample-ProdKeys.xml
$msdn.Your_Product_Keys.Product_Key.Count
# Initialise the Hash Table
$lookup = @{}
$product = read-host “what product are you using?”
$i = 0
foreach ($item in $msdn.Your_Product_Keys.Product_Key)
{
if ($item.name -like “*$product*”)
{
$lookup = $lookup + @{$i=$item.name}
write-host $i “:” $item.name
}
$i ++
}
$ID = read-host “Please enter the number of the product you want”
$msdn.Your_Product_Keys.Product_Key[$ID].Key | clip
write-host ($msdn.Your_Product_Keys.Product_Key[$ID].Name) “(“($msdn.Your_Product_Keys.Product_Key[$ID].Key)”)” -foregroundcolor “cyan”
The first thing, was to change where we increment the $i variable. I found during testing that we were returning the incorrect number to retrieve the details from the XML document. Incrementing at the end of the foreach corrected this oversight. We’ve also removed displaying the Product Key until the end of the script, to make things neater.
The main new feature has been to use an associative array, or hash table, to store our ID number and Product Name. The ID number identifies which node in the XML document our product is stored in.
Once, the hash table has been built with a list of potential products, the user is prompted to enter the ID number of the specific product. The ID is then used to lookup the Product’s Name and Key form the XML document, which is then displayed on screen and put in the clipboard buffer by using the clip.exe utility available on Windows 2003 Server and Vista.