使用“使用PowerShell运行”执行时,在另一个脚本中调用函数

问题描述 投票:43回答:2

我在'library'文件中有函数可以从我的'worker'脚本中调用。

图书馆档案

function ShowMessage($AValue)
{
  $a = new-object -comobject wscript.shell
  $b = $a.popup( $AValue )
}

工人档案

. {c:\scratch\b.ps1}

ShowMessage "Hello"

在PowerShell IDE中运行'worker'脚本时工作正常,但是当我右键单击worker文件并选择'Run with PowerShell'时,它找不到函数'ShowMessage'。两个文件都在同一个文件夹中。可能会发生什么?

function powershell
2个回答
73
投票

在worker文件中更改为:

. "c:\scratch\b.ps1"

ShowMessage "Hello"

正如@RoiDanton所述:

使用相对路径时的注意事项:不要忘记在路径前添加一个点。 ” \ b.ps1" 。

第一个点是用于修改范围的运算符,在该上下文中它与路径无关。见Dot Source Notation


14
投票

在您的工作文件中,点源库文件,这将把所有内容(函数,变量等)加载到全局范围,然后您就可以从库文件中调用函数。

=================== 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 ======================
© www.soinside.com 2019 - 2024. All rights reserved.