Freigeben über


How to detect the .NET Framework directory using PowerShell

As 64-bit machines become mainstream, one of the problems that developers run into is dealing with registry keys and directories. This is because many applications and runtimes are designed to run on both 64-bit and WOW64. The problem comes about because the same application or runtime is installed in two different directories or has two separate entries in the Windows Registry (both 32-bit version and 64-bit version).

Take the .NET Framework for example. On a 64-bit operating system, the 32-bit version of the framework is installed in

C:\Windows\Microsoft.NET\Framework\v2.0.50727

while the 64-bit version of the framework on the same machine is installed in:

C:\Windows\Microsoft.NET\Framework64\v2.0.50727

To take this example further, let's say that as part of your application's setup, you have hard-coded the location of the .NET Framework. There is a good chance now that when you migrate your application to 64-bit, your setup application is broken.

If you are using PowerShell as part of your setup application, you can detect the directory of the .NET Framework, as shown below. The Get-FrameworkDirectory cmdlet returns the default .NET Framework directory regardless of whether you are running on 32-bit or 64-bit.

 function Get-FrameworkDirectory()
{
    $([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory())
}

In the sample below, I'm using the Get-FrameworkDirectory cmdlet to find the location of aspnet_regsql.exe.

 function Create-SQLASPNETMembership
{
    Write-Host "Create the ASPNETDB SQL Server database for the membership system"
    $frameworkDir = Get-FrameworkDirectory
    Set-Alias aspnet_regsql (Join-Path $frameworkDir "aspnet_regsql.exe")
    aspnet_regsql -S DinnerNow -E -A all    
}

Habib Heydarian.