我有一个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按顺序(自上而下)处理,因此函数定义需要在函数调用之前:
function email($text){
#email $text
}
#Do things |
foreach{
email($_)
}
它可能在ISE中工作正常,因为您在内存中的函数定义仍然来自先前的运行或测试。
在函数调用方面,PowerShell在以下方面与其他编程语言完全不同:
Function func($para1){
#do something
}
func "arg1" #function-call
在ISE中,函数调用下面定义的函数可能看起来有效,但是(请注意)它是上一次运行时内存中的缓存函数定义,所以如果你更新了函数,那么你就搞砸了。