How to Call Functions in Powershell – The Right Way

How to Call Functions in Powershell – The Right Way

This applies when your function is in a different file than the program you are running. How do you proplery “include” functions in other files and directories?

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:

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

cls
$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))"
</pre>

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.

<pre>
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
}
</pre>

Runtime results:

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

 

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

<pre>
Write-Host "Path call in Write-Host = $(GetDirectoryFromPath($myFileName))"
</pre>

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

Uncategorized  

Leave a Reply