gpt4 book ai didi

powershell - 从命令行调用PowerShell函数

转载 作者:行者123 更新时间:2023-12-01 17:58:39 24 4
gpt4 key购买 nike

假设我的文件系统上有以下 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 之前的 .)——用大花括号括起来的脚本 block {...}:

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

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

24 4 0
文章推荐: Java - 将 List 转换为 List