Get-ScriptDirectory

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
Nillth
Posts: 11
Joined: Thu Aug 01, 2013 6:14 pm
Location: Melbourne, Australia

Get-ScriptDirectory

Post by Nillth » Thu Jun 08, 2017 4:10 pm

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. }

Locked