2011-10-31 68 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 –