Powershell脚本无法识别我的功能

lai*_*ha0 16 powershell service exe

我有一个powershell脚本,它解析文件并在检测到某种模式时发送电子邮件.我在函数内部设置了电子邮件代码,当我从ISE运行它时,它都可以正常运行,但我使用PS2EXE能够将脚本作为服务运行,但它无法识别函数"email".我的代码看起来与此类似

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

function email($text){
    #email $text
}
Run Code Online (Sandbox Code Playgroud)

当我将它转换为exe并运行它时,我收到此错误:

The term 'email' is not recognized as teh 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.
Run Code Online (Sandbox Code Playgroud)

JNK*_*JNK 31

Powershell按顺序(自上而下)处理,因此函数定义需要在函数调用之前:

function email($text){
    #email $text
}

#Do things | 
foreach{
    email($_)
}
Run Code Online (Sandbox Code Playgroud)

它可能在ISE中工作正常,因为您在内存中的函数定义仍然来自先前的运行或测试.


Edd*_*mar 7

在函数调用方面,PowerShell 在以下方面与其他编程语言有很大不同:

  1. 将参数传递给函数时,不允许使用括号(如果 Set-StrictMode 设置为 -version 2.0 或更高版本/最新,则会引发解析错误),但是,必须使用带括号的参数来调用方法,该方法可以是 .NET 方法或用户定义的方法(在类中定义 - 在 PS 5.0 或更高版本中)。

  2. 参数以空格分隔,而不是逗号分隔。

  3. 请注意定义函数的位置。由于 PowerShell 按自上而下的顺序逐行处理,因此必须在调用该函数之前定义该函数:

        Function func($para1){
              #do something
        }
        func "arg1"  #function-call
    
    Run Code Online (Sandbox Code Playgroud)

在 Windows PowerShell ISE(或 Visual Studio Code)中,如果函数调用似乎正在工作,即使函数定义是在函数调用下面定义的,(注意)这是因为它是从先前的执行中缓存在内存中的,一旦您更新函数定义,它也会失败。