Stupid Profile Trick: $PROFILE as Module

I’m spending a lot of time on my $PROFILE for some reason.  Don’t tell my boss. :)

Anyhow, we know that

  • Get-Module will get you a list of modules, and
  • Get-ChildItem Function:\ | Select-Object –Property Name, Module will show you what functions you have loaded from those modules.

However, functions loaded in $PROFILE won’t show up with a Module name because $PROFILE is a .PS1 file (PowerShell script), not a .PSM1 file (PowerShell script module).   Here’s a simple recipe to add ‘Microsoft.PowerShell_profile.ps1’ as the module for functions loaded in $PROFILE.

  1. Move all your functions to the top of your $PROFILE, after your comment-based help (if any) and parameter statement (if you have one).

  2. Add this line right after the functions:

     if ($global:profilePsm1) { return; }
    
    
  3. Add this snippet at the end:

     # import profile as module to get commands by module
    
    if (!$global:profilePsm1)
    {
    
        $global:profilePsm1 = "$env:Temp\Microsoft.PowerShell_profile.ps1.psm1"
        Copy-Item -Force $profile $global:profilePsm1;
        Get-Sha256Hash $global:profilePsm1 > "$global:profilePsm1.sha256";
        Import-Module $global:profilePsm1;
        Remove-Variable -Name profilePsm1 -Scope Global -Force -ErrorAction SilentlyContinue;
    
    } # if (!$global:profilePsm1)
    
    

Now, why would you want to do this?  Like I said in the title, it’s a stupid trick.  I may find a valid use for it later, but for now, I just think it’s cool that I can see what functions my profile loaded:

 Get-Command -Module ($profile -replace '.*\\')