5

I have a simple problem. My powershell script contains a couple of functions and the script calls these functions no problem.

However, when I try to run powershell from the command line to execute my script, I get the error;

The term 'MyFunction' is not recognized as the name of a cmdlet....'

Everywhere tells me I need to run my script like so from the command line for it to work;

powershell "& "'C:\My Path\script.ps1'"

This runs the script but the functions still do not work. I get the errors wherever my script calls one of the functions. What am I doing wrong? I have even gone as far as creating another script with a single line in it that just says;

. C:\My Path\script.ps1

This again works fine but then when run through the command line it fails with the same errors. Any help with this would be greatly appreciated!

EDIT: The function is defined like this;

function MyFunction ($id1, $id2) {
    ....
}

And it is called like this;

MyFunction $var1 $var2

The following script file resolved my issue and can be run from the command line fine;

Import-Module 'C:\My Path\script.ps1'
MyStartFunction  # calls other functions

powershell "& "'C:\My Path\AboveScriptFile.ps1'"
4
  • Can you show the contents of the script with MyFunction definition? Commented Jul 9, 2014 at 10:54
  • I have edited the post to reflect this Commented Jul 9, 2014 at 10:56
  • And do you want to call the function from the command line after executing the script or from within the script? Commented Jul 9, 2014 at 11:02
  • From within the script. I have added the below answer to the top of my script that runs . C:\My Path\script.ps1 and it has worked. Commented Jul 9, 2014 at 11:06

1 Answer 1

9

Use Import-Module cmdlet in powershell session(window):

Import-Module 'C:\My Path\script.ps1'

then you can run MyFunction $var1 $var2 for the duration of that session.

If you want your script to execute a function contained within it, then add the following line to the bottom. It assumes you are passing two arguments in when executing the script( ie. powershell 'C:\My Path\script.ps1' "value1" "value2")

MyFunction $args[0] $args[1]
Sign up to request clarification or add additional context in comments.

2 Comments

I added this to my short script that runs the main script and this works. Thank you!
Note that if you are using Import-Module from a prompt to use MyFunction there, and want to change the function, you need to use Remove-Module script where 'script' is module name / file name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.