$env:HOME doesn’t work in PowerShell $PROFILE

Today I wanted to setup my PowerShell $PROFILE to make it easier to work with all the modules I learned about at the PowerShell Summit. I wanted to add an additional path to the environment variable $PSModulePath. Something that should be a picece of cake.

I store additional modules in the folder ‘Documents\WindowsPowerShell\Modules’ under my userdirectory (C:\Users\Joakim). So simply joining the path using Join-Path and add the result to $ENV:PSModulePath should do the trick:

$env:PSModulePath += ';'+ (Join-Path -Path ${env:HOME} -ChildPath 'Documents\WindowsPowerShell\Modules')

Unfortunately that didn’t work. And it confused me. Executing this on the PowerShell commandline worked fine, but when I put the line above in my $PROFILE it gave me this error:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\Joakim\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:3 char:44
+ $env:PSModulePath += ';'+ (Join-Path -Path ${env:HOME} -ChildPath 'Do ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Join-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

I understand what the error says and apparently the environment variable HOME is not instantiated when the $PROFILE is executed. This really confuses me. I already have the following line in my profile and it workes like a charm:

[System.Environment]::SetEnvironmentVariable('PATH',"C:\Users\Joakim\SkyDrive\Util;$env:PATH")

So environment variables are available when $PROFILE is executing… After a bit of frustration I changed from using

$env:HOME

to using

$env:USERPROFILE

and then it works!

So a word of advise if you want to find the users homedirectory when in the context of $PROFILE. Do not use $env:HOME

If anyone can explan when the HOME variable is instatiated vs the USERPROFILE… I’m listening 😉