0

I've been putting my first powershell scripts together for the last couple of hours and I keep seeing an error that I can't seem to get to the bottom of.

I'm using the Powershell ISE tool to write and run the scripts.

To see if its something in my script I've created a super simple test script and I'm seeing the same problem. The entire test script is:

Test;

function Test
{
    New-Item C:\Users\jgreen\Desktop\jammer\ -type directory
}

When I hit the Run Script button the error produced is:

Test : The term 'Test' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct 
and try again.

If I simply hit the Run Script button again, it work and does the job. I simply do not understand what is wrong. I simply don't get it. Is there a problem with my script or not?

Why would a script that works bomb out the first time after opening the script in PS ISE?

2 Answers 2

5

You are calling the function before it is defined. The reason it works the second time, is a result of the first run. When it is ran the first time it's defining the function, so when you run the script the second time it knows what the function is.

Sign up to request clarification or add additional context in comments.

4 Comments

Urgh, how ridiculous. I guess the best thing to do then is pull in the functions as an include.
@Jammer You'll want to look into "dot sourcing", see Get-Help about_Scripts
Thank you, will go and check that now.
@Jammer Just make sure you dot source before you call the function :)
2

You need to declare your function before you invoke it. It works the second time because then it's been declared. Think of how this would work if you were just at a powershell command line and you typed: "Test;" What would you expect to happen?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.