Why do I need to have my functions written first in my PowerShell script?

前端 未结 6 971
忘掉有多难
忘掉有多难 2020-12-29 01:06

I have a script that I am utilizing functions to wrap parts of the code that allow me to move through the sections at a specified point. What I have found is that I have to

6条回答
  •  孤城傲影
    2020-12-29 01:36

    Remember that in general, what works in a script should work at the command line.

    This was not true in CMD. GOTO and FOR %I IN (...) DO %%I are two examples.

    In PowerShell, I can run commands at the command line until I get the result I want, then paste the history in to a script, then edit out the extraneous bits.

    Also, I can take a script that isn't working correctly, paste it in to an interactive shell, and study the resulting state.

    At the interactive command line, there's no way you could write this:

    F
    function F { "Hello, World!" }
    

    However, when reading a script, I want to read the top-level code first, and then see more detail as I scroll down. One approach is:

    function Main 
    {
        F
    }
    
    function F
    {
        "Hello, World!"
    }
    
    Main
    

提交回复
热议问题