Powershell Function Not Recognised

懵懂的女人 提交于 2019-12-13 06:48:44

问题


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?


回答1:


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.




回答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?



来源:https://stackoverflow.com/questions/33351096/powershell-function-not-recognised

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!