在PowerShell ISE中调用函数

28

有人能告诉我为什么我不能在PowerShell脚本中调用函数吗?以下是我的代码:

Write-Host "Before calling Function."

testFunction

function testFunction()
{ 
    Write-Host "Function has been called"
}
运行上述代码时,我收到以下错误信息:
testFunction : 无法将“testFunction”识别为 cmdlet、function、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请验证路径是否正确,然后重试。 位于 C:\Users\andrew.short\Documents\Powershell\Backups\functionTest.ps1 的第 3 字符处 + testFunction + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (testFunction:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
我相信在同一个 PowerShell 脚本中调用函数肯定是可行的。请有人帮忙吗?

3
哦,实际上我认为我可能已经发现了问题所在。我认为在调用代码之前,必须先存在该函数。 - ED209
1
是的...这应该可以工作:`Write-Host "在调用函数之前。"function testFunction { Write-Host "已调用函数" }testFunction` - Hackerman
@Ed209 没错。 - Ansgar Wiechers
1个回答

61

在使用函数之前,必须先声明该函数。

Write-Host "Before calling Function."

function testFunction {
    Write-Host "Function has been called"
}

testFunction

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接