从命令行调用PowerShell函数

4

假设在我的文件系统中有以下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
1个回答

7

脚本文件 c:\say-hello.ps1 的作用范围在脚本终止时结束。如果您希望其内容在当前范围内运行,即花括号 {...} 包裹的脚本块内,可以使用点操作符(注意 PS1 前面的.)载入该文件:

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

我有一个从PowerShell调用的函数,如下所示: Expand-ZIPFile –File “E:\MYDOC.zip” –Destination “E:\New MYDOC”在PowerShell中这样做是可以的,但是通过上述方法从命令行执行时会出现错误“Missing expression after unary operator '_'”。有什么建议吗? - choudhury smrutiranjan parida
你的示例中似乎同时使用了“美化”的破折号和引号:。我建议再次尝试使用 ASCII 中的 -" 来运行 cmd - jscott
我有一个函数:function Expand-ZIPFile($file, $destination) { $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($item in $zip.items()) { $shell.Namespace($destination).copyhere($item) } } - choudhury smrutiranjan parida

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