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.

  1. #Sample function that provides the location of the script
  2.  
  3. function Get-ScriptDirectory
  4.  
  5. {
  6.  
  7. <#
  8.  
  9.     .SYNOPSIS
  10.  
  11.         Get-ScriptDirectory returns the proper location of the script.
  12.  
  13.  
  14.  
  15.     .OUTPUTS
  16.  
  17.         System.String
  18.  
  19.    
  20.  
  21.     .NOTES
  22.  
  23.         Returns the correct path within a packaged executable.
  24.  
  25. #>
  26.  
  27.     [OutputType([string])]
  28.  
  29.     param ()
  30.  
  31.     if ($hostinvocation -ne $null)
  32.  
  33.     {
  34.  
  35.         Split-Path $hostinvocation.MyCommand.path
  36.  
  37.     }
  38.  
  39.     elseif ($script:MyInvocation.MyCommand.Path -ne $null)
  40.  
  41.     {
  42.  
  43.         Split-Path $script:MyInvocation.MyCommand.Path
  44.  
  45.     }
  46.  
  47.     else
  48.  
  49.     {
  50.  
  51.         $(Get-Location).path
  52.  
  53.     }
  54.  
  55. }