Powershell script not recognizing my function

后端 未结 2 1483
予麋鹿
予麋鹿 2020-12-09 09:55

I have a powershell script that parses a file and send an email if it detects a certain pattern. I have the email code setup inside a function, and it all works fine when I

相关标签:
2条回答
  • 2020-12-09 10:35

    When it comes to the Function-Calls, PowerShell is fairly different from other programming-languages in the following ways:

    1. When passing the arguments to a function, parentheses are NOT allowed (and will raise a parse error if Set-StrictMode is set to -version 2.0 or above/Latest), however, Parenthesised arguments must be used to call a method, which can either be a .NET method or a user defined method (defined within a Class - in PS 5.0 or above).
    2. Parameters are space-separated and not comma separated.
    3. Be careful in where you define the function. As PowerShell sequentially processes line-by-line in top-down order, hence the function must be defied before that function is called:

          Function func($para1){
                #do something
          }
          func "arg1"  #function-call
      

    In ISE, function defined below the function-call may appear as working but (beware) it's the cached function definition in memory from a previous run, so if you have updated the function you are screwed.

    0 讨论(0)
  • 2020-12-09 10:39

    Powershell processes in order (top-down) so the function definition needs to be before the function call:

    function email($text){
        #email $text
    }
    
    #Do things | 
    foreach{
        email($_)
    }
    

    It probably works fine in the ISE because you have the function definition in memory still from a prior run or test.

    0 讨论(0)
提交回复
热议问题