Use different techniques to determine a PowerShell script's directory: try `$PSScriptRoot`, `$MyInvocation.MyCommand.Path`, `$ExecutionContext.SessionState.Module.Path` and `$PWD`.
✓ Published0🌍 Public
Aaniston
Last edited May 2, 2014
Created on Feb 8, 2017
This example demonstrates a PowerShell script that determines its own directory using four distinct fallback techniques. It checks the `$PSScriptRoot` automatic variable first, then falls back to `$MyInvocation.MyCommand.Path`, followed by `$ExecutionContext.SessionState.Module.Path`, and finally defaults to `$PWD`. The code uses PowerShell’s built-in `Get-Variable` cmdlet and `Split-Path` function to extract and normalize the directory path from each source. It shows how to handle various execution contexts, such as scripts run directly, invoked from modules, or executed interactively, prioritizing the most reliable method first.
AI-generated description