Search code examples
windowspowershellpathconfiguration-files

Editing powershell prompt when user profile file doesn't exist


I want to edit my Powershell prompt, as discussed here https://superuser.com/questions/1259900/how-to-colorize-the-powershell-prompt. However, my $profile variable references a path which does not exist, C:\Users\ferdi\OneDrive\Documenti\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. Specifically, the WindowsPowerShell folder does not exist. How do I find the true location of my $profile, so that I can edit it and change my prompt?

Thanks a lot!


Solution

  • The value of the automatic $PROFILE variable is the true location of your profile file, more accurately of the profile file for the current user (you) and the current host (the application hosting PowerShell, typically a console / terminal window).

    • For more information, including about the other profile files, see the conceptual about_Profiles help topic.

    • Even though $PROFILE is a string, it is decorated with properties that contain all profile paths, and a simple way to show them all is
      $PROFILE | Select-Object *, or, more conceptually accurate,
      $PROFILE | Get-Member -MemberType NoteProperty, as lit notes.

    It is just that PowerShell doesn't create any profile files by default, and it doesn't even create the directories for them.

    • To create your $PROFILE file on demand - including its directory - use the following:

      if (-not (Test-Path $PROFILE)) {
        New-Item -Force $PROFILE 
      }
      
      • The Test-Path call guards against accidentally replacing an existing profile, because New-Item -Force not only creates parent directories as needed, but also replaces any existing file with a new, empty one.

    To then edit your profile with Visual Studio Code, for instance, run code $PROFILE or, if no custom text editor is installed, use notepad $PROFILE.

    • Either way, if there's a chance that the file's content will (possibly over time) contain non-ASCII characters (e.g., é), be sure to save the file as UTF-8 with BOM, which is required for Windows PowerShell to read it correctly, and also works in PowerShell (Core) 7.