Page 1 of 1

Get-ScriptDirectory

Posted: Thu Jun 08, 2017 4:10 pm
by Nillth
Just a minor update to the Built-in Snippit I thought I would share.

When developing code/debugging and running just a section, the built in Get-ScriptDirectory throws an error as the the values it is looking for do not exist, this will return the current working directory that the PowerShell Session Console is in.

Code: [Select all] [Expand/Collapse] [Download] (Get-ScriptDirectory.ps1)
  1. #Sample function that provides the location of the script
  2. function Get-ScriptDirectory
  3. {
  4. <#
  5.     .SYNOPSIS
  6.         Get-ScriptDirectory returns the proper location of the script.
  7.  
  8.     .OUTPUTS
  9.         System.String
  10.    
  11.     .NOTES
  12.         Returns the correct path within a packaged executable.
  13. #>
  14.     [OutputType([string])]
  15.     param ()
  16.     if ($hostinvocation -ne $null)
  17.     {
  18.         Split-Path $hostinvocation.MyCommand.path
  19.     }
  20.     elseif ($script:MyInvocation.MyCommand.Path -ne $null)
  21.     {
  22.         Split-Path $script:MyInvocation.MyCommand.Path
  23.     }
  24.     else
  25.     {
  26.         $(Get-Location).path
  27.     }
  28. }