2011-10-31 69 views
1

我有包括另一脚本功能:第二级包括

function include-function($fileName) 
{ 
    .$fileName 
} 

我保存这个功能在另一个脚本

从我的主脚本我想先有这个脚本,然后包括其他脚本:

."c:\1.ps1"       #include first file 
include-function "c:\2.ps1"   #call function to include other functions 
xtest "bbb"       #function from 2.ps1 that should be included 

问题是,2.ps1中的函数xtest在主脚本中不可见,它只在include函数的作用域中可见。有没有办法将xtest传递给主脚本?

我的包含函数并不真正加载文件(它从API获取它作为字符串),所以我不能直接从主脚本调用它。作为一种变通方法我只是改变了一个文件包括功能回到我的内容,然后从主脚本我称之为调用表达式(包括功能“C:\ 2.ps1”)

感谢

回答

3

的解释如果在2.ps1中,你声明你的变量和函数为全局变量,它们将在全局范围内可见,这是你的变量和函数的范围。

为例的2.ps1:

$global:Var2="Coucou" 

function global:Test2 ([string]$Param) 
{ 
    write-host $Param $Param 
} 

使用test.ps1

function include-function($fileName) 
{ 
    .$fileName 
} 

Clear-Host 

include-function "c:\silogix\2.ps1" 

Test2 "Hello" 

给出:

Hello Hello 

当你标记在PowerShell中V2.0您的问题最好看看模块秒。使用模块将以最佳结构化程序结束,参见about_Modules

+0

正是我需要的,非常感谢,JPBlanc –