How to Call Functions in Powershell – The Right Way

My secret is to use the $PSScriptRoot built-in variable.  If you don’t fully qualify the path, then I’ve seen issues when you run Powershell in different directories, it sometimes cannot find the function.  On the other hand, it’s bad to fully qualify the function filename, because then you cannot easily transfer the scripts to another computer that uses a different disk structure.

So I always fully qualify the function, but with a variable that uses the directory of the main program.

First here is the program that calls the function:

### this is the include statement for the file that contains your functions
. "$($PSScriptRoot)\DemoSharedFunctions.ps1"       

$myFileName = "C:\users\JohnDoe\My Documents\Abcde.txt"
$pathOnly = GetDirectoryFromPath($myFileName)
$fileOnly = GetFilenameFromPath($myFileName)
Write-Host "`$myFileName=$myFileName"
Write-Host "`$pathOnly=$pathOnly"
Write-Host "`$fileOnly=$fileOnly"

Write-Host "Path call in Write-Host = $(GetDirectoryFromPath($myFileName))"

Here is the function (filename=\DemoSharedFunctions.ps1″.  Sometimes I have trouble remembering the exact syntax of the split-path command; so I made two easy to remember function names.

Function GetDirectoryFromPath($Path)
$testpath = split-path $Path
### this next line is here just so you can play with it and see the value of the internal variable
#Write-Host "`$PSScriptRoot=$PSScriptRoot"   
return $testpath

Function GetFilenameFromPath($Path)
$filename = split-path $Path -leaf
return $filename

Runtime results:

$myFileName=C:\users\JohnDoe\My Documents\Abcde.txt
$pathOnly=C:\users\JohnDoe\My Documents
Path call in Write-Host = C:\users\JohnDoe\My Documents


I included this line (from the above calling script) to explain one more thing:

Write-Host "Path call in Write-Host = $(GetDirectoryFromPath($myFileName))"

This demonstrates how you can call a function directly inside of a Write-Host statement, just by wrapping it like this $(xxx)

Filed under: Powershell