Powershell脚本无法识别我的功能

问题描述 投票:16回答:2

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

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

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

当我将它转换为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.
powershell service exe
2个回答
31
投票

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

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

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

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


2
投票

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

  1. 将参数传递给函数时,不允许使用括号(如果将Set-StrictMode设置为-version 2.0或更高/最新,则会引发解析错误),但是,必须使用带括号的参数来调用方法,该方法可以是.NET方法或用户定义的方法(在类中定义 - 在PS 5.0或更高版本中)。
  2. 参数是空格分隔的,不是逗号分隔的。
  3. 在定义函数的位置要小心。由于PowerShell按照自上而下的顺序逐行进行处理,因此必须在调用该函数之前禁用该函数: Function func($para1){ #do something } func "arg1" #function-call

在ISE中,函数调用下面定义的函数可能看起来有效,但是(请注意)它是上一次运行时内存中的缓存函数定义,所以如果你更新了函数,那么你就搞砸了。

© www.soinside.com 2019 - 2024. All rights reserved.