Ensuring a PowerShell script will always run in a 64 bit shell

Someone on Jabbr earlier today was struggling a bit with a NuGet init.ps1 script while trying to work with the IIS module. They thought the NuGet Package Manager shell was 64 bit, but in fact it’s a 32 bit shell as Visual Studio is itself 32 bit and will remain that way for the foreseeable future. So, if I have a dependency on some 64 bit binary module, how can I ensure that the script will get run in the right environment? Well, here’s some “stub” script that you can put at the top of your ps1 file that will detect its environment and relaunch itself in a 64 bit shell, passing along any arguments that were given.

I’d suggest keeping your 64 bit scripts in a separate ps1 and calling them from init.ps1 to do the work. Because the script will be relaunched in a 64 bit shell, you won’t have access to the package manager console intrinsics like $DTE, nor can you pass any “live” objects to the essentially external script. Stick to strings and other primitives like [int] and [bool] etc.

# am I running in 32 bit shell?
if ($pshome -like "*syswow64*") {
    write-warning "Restarting script under 64 bit powershell"

    # relaunch this script under 64 bit shell
    # if you want powershell 2.0, add -version 2 *before* -file parameter
    & (join-path ($pshome -replace "syswow64", "sysnative") powershell.exe) -file `
        (join-path $psscriptroot $myinvocation.mycommand) @args

    # exit 32 bit script

# start of script for 64 bit powershell

write-warning "hello from $pshome"
write-warning "My original arguments $args"

Also available on poshcode: http://poshcode.com/3827

Disclaimer: I’ve tested this with PowerShell 3.0 only.

blog comments powered by Disqus

About the author

Irish, PowerShell MVP, .NET/ASP.NET/SharePoint Developer, Budding Architect. Developer. Montrealer. Opinionated. Montreal, Quebec.

Month List

Page List