[英]Call a function in another script when executing using 'Run With PowerShell'
I have functions in a 'library' file to be called from my 'worker' script. 我在'library'文件中有函数可以从我的'worker'脚本中调用。
Library File 图书馆档案
function ShowMessage($AValue)
{
$a = new-object -comobject wscript.shell
$b = $a.popup( $AValue )
}
Worker File 工人档案
. {c:\scratch\b.ps1}
ShowMessage "Hello"
Running the 'worker' script works fine when in the PowerShell IDE but when I right-click the worker file and choose 'Run with PowerShell' it cannot find the function 'ShowMessage'. 在PowerShell IDE中运行'worker'脚本时工作正常,但是当我右键单击worker文件并选择'Run with PowerShell'时,它找不到函数'ShowMessage'。 Both files are in the same folder. 两个文件都在同一个文件夹中。 What might be happening? 可能会发生什么?
In the worker file change to this: 在worker文件中更改为:
. "c:\scratch\b.ps1"
ShowMessage "Hello"
As @RoiDanton mentioned below: 正如@RoiDanton所述:
Attention when using relative pathing: Don't forget to prepend a dot before the path . 使用相对路径时的注意事项:不要忘记在路径前添加一个点。 ".\\b.ps1". ” \\ b.ps1" 。
The first dot is an operator used to modify the scope and in that context it has nothing to do with paths. 第一个点是用于修改范围的运算符,在该上下文中它与路径无关。 See Dot Source Notation . 请参阅点源表示法 。
In your worker file, dot-source the library file, this will load all content (functions, variables, etc) to the global scope, and then you'll be able to call functions from the library file. 在您的工作文件中,点源库文件,这将把所有内容(函数,变量等)加载到全局范围,然后您就可以从库文件中调用函数。
=================== Worker file ==========================
# dot-source library script
# notice that you need to have a space
# between the dot and the path of the script
. c:\library.ps1
ShowMessage -AValue Hello
=================== End Worker file ======================
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.