Assistance at your fingertips...

Correctly Setting the PowerShell Root


⭐ You should NOT set $root or $PSScriptRoot in your profile

Your profile runs in contexts where:

  • There is no script file
  • There is no script root
  • There is no module root
  • There is no predictable working directory
  • You might be in ISE, pwsh, Windows PowerShell, or a remote session
  • You might be in OneDrive or not
  • You might be in a server/DC environment where $HOME is restricted

If you set a $root variable in your profile, you would be lying to your scripts about where they live.

❌ Example of what goes wrong

If your profile sets:

$root = "C:\PowerShell"

Then you run a script from:

D:\PowerShell\Scripts\MyScript.ps1

Your script will think its root is:

C:\PowerShell

That breaks:

  • Script‑local module loading
  • Relative paths
  • Logging paths
  • Config file paths
  • Any script that uses $root
  • Any script that uses your hybrid module loader

This is why $PSScriptRoot exists — it is context‑aware, and the profile is not.


⭐ Why $PSScriptRoot is NOT set in your profile

Because:

$PSScriptRoot only exists when PowerShell is executing a .ps1 or .psm1 file.`

Your profile is not a script being executed — it is a script being dot‑sourced into the session.

Dot‑sourced files do not get $PSScriptRoot.

This is by design.


⭐ The correct pattern

Inside your function or script:

$root = if ($PSScriptRoot) { $PSScriptRoot } else { Get-Location }

This is the only correct, portable, enterprise‑safe way to determine the script root.

✔ When running a script

$PSScriptRoot is correct.

✔ When running interactively

Get-Location is correct.

✔ When dot‑sourced

Get-Location is correct.

✔ When running from a scheduled task

$PSScriptRoot is correct.

✔ When running on servers/DCs

$PSScriptRoot is correct.

✔ When running from OneDrive

$PSScriptRoot is correct.

✔ When running from C: or D:

$PSScriptRoot is correct.

This is why the fallback logic is essential.


⭐ Final Answer:

❌ Do NOT set $root in your profile

❌ Do NOT try to set $PSScriptRoot manually

❌ Do NOT store script paths in your profile

✔ DO use this inside a function or PowerShell script:

$root = if ($PSScriptRoot) { $PSScriptRoot } else { Get-Location }

✔ DO keep your hybrid module loader inside scripts

✔ DO keep your profile clean and environment‑agnostic


…a product of Copilot and several hours of working through the various scenarios Senior Admins experience. -Patrick