2012-10-29

Can I use PowerShell functions before defining them

Yes and NO!

As I was learning syntax and intricacies of PowerShell, one of the first things I was told was that if I wanted to use a function, I had to define it first, which meant that I had to structure my script so that functions would be on top and the main script at the bottom. Obvious reason is that PowerShell parses the script sequentially starting from top, working its way to the bottom. This fact remains the same.

If you were always using PowerShell ISE and were not calling your script from the command line, this behavior would come as a surprise to you, because PowerShell ISE does not care where in the script the function is located. There is a dated but still a good intro to functions at this PowerShellPro.com link that mentions this but does not clarify the point. You can see that in the comments.

So, should you define your functions before using them? Sure! Do not bet against command line.