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 Feb 8, 2017
Created on Feb 8, 2017
This example demonstrates a PowerShell script that attempts to locate its own directory using four different techniques in a fallback sequence: `$PSScriptRoot`, `$MyInvocation.MyCommand.Path`, `$ExecutionContext.SessionState.Module.Path`, and finally `$PWD`. The code defines a function `Get-ScriptPath` that checks each variable in order, using `Split-Path` to extract the parent directory when necessary. It shows the logic for handling environments where certain automatic variables may be unavailable, such as when the script is invoked from a module or interactive session. The example relies on PowerShell’s built-in `Get-Variable` cmdlet and conditional checks to progressively resolve the path.
AI-generated description