Search code examples
powershellscriptingenvironment-variablespowershell-5.0

PowerShell ISE not recognizing $profile variables


In my $profile directory, I have a few custom variables, as well as the default variables, such as $root (which equals "C:\"), etc. One custom variable I have holds the filepath to my desktop, so I can easily reference the path, and also not have to create the variable every time I start up PS. If I attempt to resolve any variable value from the $profile path within ISE(both the script pane and console) it does not work. However, if I use the regular PS terminal, it works no problem. Any suggestions or explanations?


Solution

  • PowerShell ISE uses a different host profile than a standard PowerShell session. The $profile variable actually displays the profile for the CurrentUserCurrentHost profile by default, but there are four profile locations stored in this variable. Each of these locations are dot-sourced by default when you load PowerShell. You can see this by typing $profile | Get-Member -MemberType NoteProperty to see the total profiles configured:

    • AllUsersAllHosts
    • AllUsersCurrentHost
    • CurrentUserAllHosts
    • CurrentUserCurrentHost

    Before we continue, let's talk about what a PowerShell Host really is. From Microsoft:

    The host application can define the runspace where commands are run, open sessions on a local or remote computer, and invoke the commands either synchronously or asynchronously based on the needs of the application.

    So what this means is that a PowerShell Host implements a PowerShell session. This can be powershell.exe for a basic, standard host, but there could be any number of alternative applications or development tools that may implement their own PowerShell Host as well, for a number of reasons.


    The AllHosts profile locations should remain standard regardless of your PowerShell host, but different PowerShell hosts will typically set their own CurrentHost profile locations for their host. For example, powershell.exe is its own PowerShell host, and will have its own host-specific profiles, named Microsoft.PowerShell_profile.ps1. PowerShell ISE implements its own PowerShell host, and has different host-specific profiles named Microsoft.PowerShellISE_profile.ps1.

    If you want code in your profile to be host-agnostic, you should make sure to place your profile code in one of the AllHosts profiles. Host-specific code, such as things you only want to be available in the context of the ISE PowerShell host, or a VSCode PowerShell host, should go into that host-specific profile.