我有一个简单的问题。我的powershell脚本包含几个函数,脚本调用这些函数没问题。
但是,当我尝试从命令行运行powershell来执行我的脚本时,我收到错误;
The term 'MyFunction' is not recognized as the name of a cmdlet....'
无处不在告诉我,我需要从命令行运行我的脚本才能工作;
powershell "& "'C:\My Path\script.ps1'"
这会运行脚本但功能仍然不起作用。无论我的脚本调用其中一个函数,我都会收到错误。我究竟做错了什么?我甚至已经创建了另一个脚本,其中只有一行,只是说;
. C:\My Path\script.ps1
这再次正常工作,但是当通过命令行运行时,它失败并出现相同的错误。任何有关这方面的帮助将不胜感激!
编辑: 该函数定义如下;
function MyFunction ($id1, $id2) {
....
}
它被称为这样;
MyFunction $var1 $var2
以下脚本文件解决了我的问题,可以从命令行运行;
Import-Module 'C:\My Path\script.ps1'
MyStartFunction # calls other functions
powershell "& "'C:\My Path\AboveScriptFile.ps1'"
答案 0 :(得分:5)
在PowerShell会话(窗口)中使用Import-Module
cmdlet:
Import-Module 'C:\My Path\script.ps1'
然后您可以在该会话期间运行MyFunction $var1 $var2
。
如果您希望脚本执行其中包含的功能,请将以下行添加到底部。它假设您在执行脚本时传递两个参数(即。powershell 'C:\My Path\script.ps1' "value1" "value2"
)
MyFunction $args[0] $args[1]