鉴于我的文件系统上有以下 say-hello.ps1 文件:

function SayHello()
{
    return "Hello World!"
}

像这样在命令行上调用(它最终将作为 Windows 计划任务运行):
powershell -ExecutionPolicy unrestricted -command "& { c:\say-hello.ps1; SayHello }"

为什么我得到以下结果?
SayHello : The term 'SayHello' is not recognized as the 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.
At line:1 char:33
+ & { c:\say-hello.ps1; SayHello }
+                       ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (SayHello:String) [], CommandNot
   FoundException
    + FullyQualifiedErrorId : CommandNotFoundException

最佳答案

脚本文件 c:\say-hello.ps1 的范围在脚本终止时结束。如果您希望其内容在当前范围内运行,您可以点源文件(注意 PS1 之前的 .)——用 curlies {...} 括起来的脚本块:

powershell -ExecutionPolicy unrestricted -command "& { . c:\say-hello.ps1; SayHello }"

关于powershell - 从命令行调用 PowerShell 函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20804065/

10-09 00:14