Technical Notes

My online notepad

  • Social


  • Support

    Donate towards my web hosting bill!

How to check MSI version in PowerShell

Posted by Anton Khitrenovich on January 22, 2014

logo-powershellIt appears that checking MSI version in PowerShell is much less trivial than checking DLL version. Yet, the following script can do it for you. Most of the credits for the script go to this StackOverflow question.

###############################################################
# Name:         GetMsiVersion.ps1
# Description:  Prints out MSI installer version
# Usage:        GetMsiVersion.ps1 <path to MSI>
# Credits:      http://stackoverflow.com/q/8743122/383673
###############################################################
param (
    [IO.FileInfo] $MSI
)

if (!(Test-Path $MSI.FullName)) {
    throw "File '{0}' does not exist" -f $MSI.FullName
}

try {
    $windowsInstaller = New-Object -com WindowsInstaller.Installer
    $database = $windowsInstaller.GetType().InvokeMember(
        "OpenDatabase", "InvokeMethod", $Null,
        $windowsInstaller, @($MSI.FullName, 0)
    )

    $q = "SELECT Value FROM Property WHERE Property = 'ProductVersion'"
    $View = $database.GetType().InvokeMember(
        "OpenView", "InvokeMethod", $Null, $database, ($q)
    )

    $View.GetType().InvokeMember("Execute", "InvokeMethod", $Null, $View, $Null)
    $record = $View.GetType().InvokeMember( "Fetch", "InvokeMethod", $Null, $View, $Null )
    $version = $record.GetType().InvokeMember( "StringData", "GetProperty", $Null, $record, 1 )

    return $version
} catch {
    throw "Failed to get MSI file version: {0}." -f $_
}

Here is the execution sample:

C:\>powershell -ExecutionPolicy bypass -File GetMsiVersion.ps1 "C:\Program Files (x86)\Google\Update\1.3.21.79\GoogleUpdateHelper.msi"
1.3.21.79

C:\>

Enjoy!

Posted in HOWTO | Tagged: , | Leave a Comment »

How to check DLL version in PowerShell

Posted by Anton Khitrenovich on January 22, 2014

logo-powershellChecking DLL version in PowerShell is extremely easy.

Here is the script that does it for you. Note that the real code fits in a single line (lines 17-18, I just split it out for readability). Other 20+ lines are dedicated to script header, input validation and exception handling.

###############################################################
# Name:         GetDllVersion.ps1
# Description:  Prints out DLL version
# Usage:        GetDllVersion.ps1 <path to DLL>
# Author:       Anton Khitrenovich, Jan 2014
###############################################################
param(
    [string]$DLL
)

if (!(Test-Path $DLL)) {
    throw "File '{0}' does not exist" -f $DLL
}

try {
    $version =
        Get-ChildItem $DLL | Select-Object -ExpandProperty VersionInfo |
            Select-Object FileVersion | Select-Object -ExpandProperty FileVersion

    return $version
} catch {
    throw "Failed to get DLL file version: {0}." -f $_
}

Here is the execution sample:

C:\>powershell -ExecutionPolicy bypass -File C:\GetDllVersion.ps1 "C:\Program Files\Java\jre7\bin\java.dll"
7.0.250.17

C:\>

Enjoy!

Posted in HOWTO | Tagged: , | 1 Comment »

How to run PowerShell script from Ant

Posted by Anton Khitrenovich on January 22, 2014

logo-powershellYesterday I was looking for a good recipe of how to run PowerShell script from Ant build file. Unfortunately, it seems that most of the people are looking for an advise on exactly the opposite – how to run Ant from PowerShell. So, I did some trial and error on my own, and here are the results.

The following Ant snippet executes PowerShell script MyScript.ps1 in the current directory and verifies that it did not fail. The result of the script execution is stored in myscript.out property.

<exec dir="." executable="powershell" timeout="5000" failonerror="true"
        outputproperty="myscript.out" errorproperty="myscript.error">
    <arg line="-ExecutionPolicy bypass" />
    <arg line="-File MyScript.ps1" />
</exec>
<if>
    <not>
        <equals arg1="${myscript.error}" arg2="" trim="true" />
    </not>
    <then>
        <fail message="${myscript.error}" />
    </then>
</if>

The main caveat here is the error checking. Despite the failonerror flag, the exec task will not fail in case of many errors – like compilation issues, missing parameters and other runtime errors. This happens because the task verifies invocation of PowerShell itself and not the script execution, which is handled inside PowerShell. The solution is to capture error stream into dedicated property and verify that nothing was actually written there.

Pay attention that if tag (lines 6-13) requires ant-contrib tasks library available. The same condition may be rewritten in less readable form with pure Ant:

<fail message="${myscript.error}">
    <condition>
        <not>
            <equals arg1="${myscript.error}" arg2="" trim="true" />
        </not>
    </condition>
</fail>

Another note is the bypass of default execution policy on line 3. This is not specific to Ant, but rather to PowerShell in general. There are a lot of discussions on the net about the topic, so I won’t cover it here.

Posted in HOWTO, Workarounds | Tagged: , , | 1 Comment »

Notes on creation of Windows AMI in EC2

Posted by Anton Khitrenovich on December 24, 2013

AWSCreating AMI from Windows instance in AWS is simple and easy. The whole process is well-documented, yet here are several notes that I made while experimenting.

Running Sysprep Tool
In the VMware world, you can convert a VM to a template at any moment. Deployment of multiple clones is made possible via Customization Specifications mechanism, where you define how to customize the new VM after cloning. As part of the customization process, vCenter will run Sysprep tool – after the instance was already cloned. In contrary, AWS wants you to run sysprep before the cloning, as preparation to AMI creation. You can do that via EC2ConfigService settings (see below) or manually, but former seems to be the preferred and recommended way.
The unwanted side effect of running sysprep on the original instance is that many of the original instance settings (instance name, Administrator account etc.) are actually reset during the cloning process. There are workarounds that can help you to deal with some consequences, but not all of them.

EC2ConfigService
The EC2ConfigService is Windows service provided and installed by AWS, which takes care about a lot of useful customizations behind the scenes. Examples are generation of Administrator password (one that you retrieve via “Connect” button in EC2 Management Console), setting of computer name, display of system information on the desktop wallpaper and a lot more. But the most important task is to deal with instance cloning – that is, make sure that stuff that is supposed to be unique is really unique and make this cloning process simple and easy.
Note that you cannot install this service on a Windows instance imported from other systems (for example, VMware vCenter). You’ll have to start your original instance from AWS AMI if you want to use EC2ConfigService there.

Instance Name
The name of the original Windows instance will be reset during sysprep process to the default semi-random name provided by AWS (in the form of “WIN-<something>”). The only workaround for that is to use “Set Computer Name” from EC2ConfigService settings. This flag instructs EC2ConfigService to (re)set system name according to the internal IP adrress – which remains constant during the instance lifecycle. The resulting name will not become much more readable, but at least it will not change during the AMI creation process. You’ll have to remove this flag manually on the cloned instances to set more meaningful names there.

Administrative Accounts
The Administrator account from the original instance will not make his way to the cloned instances, so any customizations made there will be lost. The workaround is to create an additional account with administrative permissions and perform the desired customizations there. There are many settings that will go this way too (for example, regional settings or pinned taskbar items), but some will survive – desktop shortcuts, windows explorer options and more.
Another tip is to choose “Keep Existing” in the “Administrator Password” section of EC2ConfigService configuration. While it won’t help you to retain current password in the new instances (because Sysprep tool on Windows 2008 resets it anyway), at least the Administrator password of your original instance will not be changed.

AMI Creation Steps
This is not an ultimate guide on how to create AMI, but rather a note/reminder to myself…

  1. Create a new EC2 instance from AWS AMI
  2. Create new administrative account and start using it instead of the build-in one
  3. (optional) Use “Set Computer Name” option from EC2ConfigService settings
  4. Customize your instance – install software, add desktop shortcuts etc.
  5. Start EC2ConfigService settings utility, go to the “Image” tab and perform the following:
    • (optional) Under “Administrator Password” section, select “Keep Existing” option
    • Click “Shutdown with Sysprep” button and confirm the prompt
  6. Wait while the Sysprep process completed and the instance shuts down
  7. Right-click the instance in the EC2 Management Console, choose “Create Image” and follow the instructions

Tip: Disk Size
When you launch an EC2 instance that you plan to convert to AMI later, pay attention to the disk size. Remember that the disk of the AMI must be at least that big, and the same applies to any instance that will be launched from the new AMI. Provisioning 10GB of spare storage in your AMI will cost you $1 per instance per month, which may be kinda painful in the yearly bill (do the math yourself).

Posted in HOWTO, Workarounds | Tagged: , , , , , | 2 Comments »

Properties resolution in Maven and its implications on Antrun plugin

Posted by Anton Khitrenovich on December 18, 2013

Two days ago I did some internal research in order to understand how do resolved properties propagate from Maven to Ant via maven-antrun-plugin. On my way I had to recall several rarely remembered facts and learn some new ones. The implications of their combination leads to pretty interesting results that are worth writing them down. At least, now I’ll know where to look for this information next time.

Fact #1
There are multiple sources for properties resolution in Maven – implicit project properties (like project.version), environment variables, user-defined properties (ones you use in properties tag or your pom.xml), Java system properties… The full list with detailed explanations is available in The Complete Reference online book.
Pay attention – when you “override” some user-defined property via command line parameter (-D), in fact you are setting a new Java system property. This works because system properties have higher precedence during properties resolution process.

Fact #2
All properties that are explicitly used in pom.xml are resolved before Maven lifecycle actually starts, even before the initialize phase. It happens when so-called “effective pom” (full project definition, including all implicit data and configuration settings propagated from parent project) is generated. BTW, you can see this in action by call mvn help:effective-pom on your project.

Implication #1
Modifications of project properties that happen during project lifecycle have no effect on the effective pom – it is just too late. Examples of such modifications include groovy scripts (via gmaven-plugin) and properties loaded from external files via maven-properties-plugin. So, why do we need them at all? Since they can be used by other plugins in runtime, when they are read directly from properties collection during plugin invocation.

Read the rest of this entry »

Posted in HOWTO | Tagged: , | 1 Comment »