从命令行调用时无法识别Powershell函数

cre*_*ive 2 powershell powershell-2.0

我有一个简单的问题。我的powershell脚本包含几个函数,该脚本调用这些函数没有问题。

但是,当我尝试从命令行运行powershell来执行脚本时,会出现错误;

The term 'MyFunction' is not recognized as the name of a cmdlet....'
Run Code Online (Sandbox Code Playgroud)

到处都告诉我,我需要从命令行像这样运行脚本,脚本才能正常工作。

powershell "& "'C:\My Path\script.ps1'"
Run Code Online (Sandbox Code Playgroud)

这将运行脚本,但是功能仍然无法正常工作。无论我的脚本调用哪个函数之一,我都会得到错误。我究竟做错了什么?我什至只创建了一个脚本,只写一行。

. C:\My Path\script.ps1
Run Code Online (Sandbox Code Playgroud)

再次运行正常,但是在命令行中运行时失败,并出现相同的错误。任何帮助,将不胜感激!

编辑:函数是这样定义的;

function MyFunction ($id1, $id2) {
    ....
}
Run Code Online (Sandbox Code Playgroud)

它被这样称呼;

MyFunction $var1 $var2
Run Code Online (Sandbox Code Playgroud)

以下脚本文件解决了我的问题,可以从命令行正常运行;

Import-Module 'C:\My Path\script.ps1'
MyStartFunction  # calls other functions

powershell "& "'C:\My Path\AboveScriptFile.ps1'"
Run Code Online (Sandbox Code Playgroud)

Raf*_*Raf 5

Import-Module在Powershell会话(窗口)中使用cmdlet:

Import-Module 'C:\My Path\script.ps1'
Run Code Online (Sandbox Code Playgroud)

那么您可以MyFunction $var1 $var2在该会话期间运行。

如果要脚本执行其中包含的功能,则将以下行添加到底部。假设您在执行脚本时要传入两个参数(即powershell 'C:\My Path\script.ps1' "value1" "value2"

MyFunction $args[0] $args[1]
Run Code Online (Sandbox Code Playgroud)