Calling a function within a ps1


This seems like a really silly question, but how do I execute a function within a.PS1 from a cmd line/terminal.

For example, I have a function in a ps1 with 2 params Name, Location.

I want to execute:

myfunction.ps1 -name "MyName" -location "London."

I know it seems odd, but I’m trying to resolve an issue with DevOps.

dot-source your .ps1 file first, then call your function.

. myfunction.ps1

You can read about dot-sourcing here

ha, i tried that but it didn’t work, then i realised i have left the call to the function within the PS1 which was throwing a error.

Edit: Actually this didn’t work.

I getting confused. I can’t .\ the ps1 file as it doesn’t know which function to execute. So i need to execute the function in the .ps1 and pass the required params

I probably should have said that i dont want load the ps1 file. I need to run inline.

Depends what your file looks like. If this is your PS1 file:

function Do-Thing {
    # ...

Then you need to do something like this:

. .\file.ps1
Do-Thing -Param $Value

The extra dot is important, as is the space after it. It’s called dot-sourcing, and essentially it imports the whole PS1 file into the current session. Any functions or variables that are defined in the PS1 become loaded in the current session. You can think of it a bit like importing a snapshot of the state of the console when the script has just finished being run through once. Once it’s imported, you then have to actually call the function. :slight_smile:

The syntax is . $filePath , so if you’re accessing something from the current location it’ll look like you’re doubling up on dots: . .\myfile.ps1

Depending on what is trying to be accomplished, you do not need to create a function inside the .ps1 file. You can accept params directly in the script and call the script with the parameters like you have in your original post.

param (

code goes here

Then call your script with the two parameters.

C:\temp\myfunction.ps1 -name "MyName" -location "London."


.\myfunction.ps1 -name "MyName" -location "London."