🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Profiles

A profile is a script that runs when PowerShell starts. It sets up the shell with functions and variables you want ready each time.

Dot-source a script to load its function

Write a script file that defines a function. Dot-source it, then call the function by name.

$profilePath = Join-Path $PSScriptRoot "MyProfile.ps1"
Set-Content -Path $profilePath -Value 'function Get-Greeting { "Hello from the profile" }'
. $profilePath
Get-Greeting

A dot-sourced variable stays available

A variable defined in a dot-sourced script stays in the session. Read it after dot-sourcing the script.

$profilePath = Join-Path $PSScriptRoot "MyProfile.ps1"
Set-Content -Path $profilePath -Value '$favoriteColor = "green"'
. $profilePath
$favoriteColor

A function can use a profile variable

A profile script can define a variable and a function together. The function reads the variable when it runs.

$profilePath = Join-Path $PSScriptRoot "MyProfile.ps1"
Set-Content -Path $profilePath -Value '$greetingWord = "Hello"', 'function Get-Greeting { "$greetingWord, friend" }'
. $profilePath
Get-Greeting

Example

$profilePath = Join-Path $PSScriptRoot "MyProfile.ps1"
Set-Content -Path $profilePath -Value '$toolName = "Helper"', 'function Show-Tool { "Tool is $toolName" }'
. $profilePath
Show-Tool
$toolName

Key points

  • Profile: a script that runs when PowerShell starts.
  • Dot-sourcing: running a script with a dot and a space before its path, so its functions and variables stay in the current session.
  • Function: a named block of code you can call by name.
  • Session: the current PowerShell run, which keeps what a dot-sourced script defines.
  • Profile script: an ordinary script file, so you can test it by dot-sourcing it before relying on it at startup.

In this example, a profile-style script defines a variable and a function, the script is dot-sourced so both stay in the session, the function prints a line using the variable, and the variable prints on its own line too.

Note

profile locations differ from machine to machine, so this lesson uses a script file you create instead of a real profile path.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you load a profile-style script so its function stays available afterwards?