[英]Putting functions in separate script and dot-sourcing them - what will the scope be
我把我的函數放在一個單獨的文件中,然后調用該文件:
$workingdir = Split-Path $MyInvocation.MyCommand.Path -Parent
. "$workingdir\serverscan-functions.ps1"
但是,如果我把腳本稱為
my-function
變量范圍(來自“my-function”)將如何? 我還應該使用$ script:變量來使變量存在於函數外部還是我也可以點源函數?
希望我不要把任何人與我的問題混淆......我試圖讓它盡可能地理解,但仍然學習所有的基本概念,所以我覺得很難解釋..
當您點源代碼時,它的行為就像該代碼仍在原始腳本中一樣。 范圍將與在一個文件中全部相同。
C:\\ functions.ps1代碼:
$myVariable = "Test"
function Test-DotSource {
$script:thisIsAvailableInFunctions = "foo"
$thisIsAvailableOnlyInThisFunction = "bar"
}
main.ps1代碼
$script:thisIsAvailableInFunctions = ""
. C:\functions.ps1
# Call the function to set values.
Test-DotSource
$script:thisIsAvailableInFunctions -eq "foo"
# Outputs True because of the script: scope modifier
$thisIsAvailableOnlyInThisFunction -eq "bar"
# Outputs False because it's undefined in this scope.
$myVariable -eq "Test"
# Outputs true because it's in the same scope due to dot sourcing.
為了達到你想要的效果,你可能需要創建一個模塊。 在模塊中,使用Export-ModuleMember
導出函數,只要您沒有顯式地將任何變量導出為模塊成員,您應該沒問題。
創建模塊后,使用Import-Module
cmdlet Import-Module
。
我的2:
通常(在過去的安迪·阿里斯門迪回答之后!上帝保佑你們!)我將所有腳本保存在$pwd
文件夾中(在系統路徑環境中添加)。 我可以從控制台調用它們而不用點源,並且在腳本結束工作后沒有腳本變量使控制台中毒。
如果你不能用簡單的腳本修改你的功能(有時它會發生)我同意Trevor的回答來創建一個模塊並在$profile
導入它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.