如何在使用'使用PowerShell运行'执行PowerShell脚本时在另一个PowerShell脚本中调用函数

如何在使用'使用PowerShell运行'执行PowerShell脚本时在另一个PowerShell脚本中调用函数

问题描述:

我开始使用PowerShell,并且正在'库'文件中创建函数以提高可读性,然后从我的'worker'脚本。如何在使用'使用PowerShell运行'执行PowerShell脚本时在另一个PowerShell脚本中调用函数

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


=================== Worker file ========================== 
. {c:\scratch\b.ps1} 

ShowMessage "Hello" 
=================== End Worker file ========================== 

运行“工人”在PowerShell的IDE时,但是当我用鼠标右键单击该工作人员文件,并选择它无法找到函数“使用PowerShell运行”脚本正常工作“ShowMessage”。这两个文件都在同一个文件夹中。这里可能会发生什么?

+0

另请注意,使用`&`调用脚本,例如。 `&“c:\ scratch \ b.ps1”`不会导入这些函数。 – ashes999 2017-08-10 21:57:11

尝试添加这样的脚本:

=================== Worker file ========================== 
. "c:\scratch\b.ps1" 

ShowMessage "Hello" 
=================== End Worker file ========================== 
+2

工作正常,谢谢。 – 2011-12-14 09:26:59

+1

使用相对路径时的注意事项:不要忘记在路径前加上一个点。 ” \ b.ps1" `。对于psh来说,这是一个很新的东西,我不知道第一个点是修改范围的操作符,在这个范围内与路径无关。请参阅[点来源表示法](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes)。 – 2017-11-03 13:02:04

在你的工人文件,点源库文件,这将加载的所有内容(函数,变量等),以在全球范围内,然后你将能够从库文件中调用函数。

=================== 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 ======================