PowerShell Program Files Environment Variable

PowerShell

Today I saw this on Twitter from Julie Blender (@#juneb_get_help): 

Need to reference the “ProgramFiles(x86)” environment variable in #PowerShell? Use ${env:ProgramFiles(x86)}.

I use this in a lot of my scripts, but I want a single variable that contains the right value whether I’m in a 64 bit shell or not.  Here’s my solution:

First, I have a function in my testing profile called is64bit, that looks like this:

PowerShell
function is64bit() {
  return ([IntPtr]::Size -eq 8)
}
PowerShell

Next, I have a get-programfilesdir function that I call that checks whether or not I’m in a 64 bit shell or not and returns the appropriate program files environment variable (ie, if I’m running on a 64 bit machine it will return “C:\Program Files (x86)”, but if I’m running on a 32 bit machine it will return “C:\Program Files”.  If I’m running in a 32 or 64 bit shell on a 64 bit machine, it will always return “C:\Program Files (x86)”.

PowerShell
function get-programfilesdir() {
  if (is64bit -eq $true) {
    (Get-Item "Env:ProgramFiles(x86)").Value
  }
  else {
    (Get-Item "Env:ProgramFiles").Value
  }
}
PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *