【问题标题】:Calling PowerShell function from command line从命令行调用 PowerShell 函数
【发布时间】:2013-12-27 16:25:06
【问题描述】:

鉴于我的文件系统上有以下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

【问题讨论】:

    标签: powershell cmd


    【解决方案1】:

    脚本文件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 很好,但从命令行执行时通过上述方法,它会给出错误“一元运算符'_'后缺少表达式。任何建议。
    • 您的示例中似乎同时包含“美化”破折号和引号:。我会再次尝试使用cmd,使用ASCII -"
    • 我有一个函数:function Expand-ZIPFile($file, $destination) { $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($ $zip.items()) 中的项目 { $shell.Namespace($destination).copyhere($item) } }
    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 2012-05-06
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多