2012-08-03 62 views
5

我寫了下面的PowerShell腳本:使PowerShell腳本運行的cmdlet在全球範圍內

function Reload-Module ([string]$moduleName) { 
    $module = Get-Module $moduleName 
    Remove-Module $moduleName -ErrorAction SilentlyContinue 
    Import-Module $module 
} 

與此腳本唯一的問題是,導入模塊僅適用該腳本的範圍內 - 它不會導入模塊在全球範圍內。有沒有什麼辦法讓腳本導入模塊,以便在腳本結束後保持它?

注意:dot-sourcing像這樣:. Reload-Module MyModuleName不起作用。

+1

您是否試過'Import-Module -cope Global'? – JohnL 2012-08-03 16:44:34

+0

'啪 - 額頭'不,我沒有。也許我應該更徹底地閱讀幫助。實際參數只是'-Global'。如果你把這個作爲答案,我會贊成並標記爲答案。 – Phil 2012-08-03 18:42:48

+0

完成!我猜,'-Scope Global'是v3.0。 – JohnL 2012-08-03 19:38:07

回答

4

從PowerShell幫助:

-Global [<SwitchParameter>] 
Imports modules into the global session state so they are available to all commands in the session. By 
default, the commands in a module, including commands from nested modules, are imported into the 
caller's session state. To restrict the commands that a module exports, use an Export-ModuleMember 
command in the script module. 

The Global parameter is equivalent to the Scope parameter with a value of Global. 


Required?     false 
Position?     named 
Default value    False 
Accept pipeline input?  false 
Accept wildcard characters? false 

V3還增加了-Scope參數,它更多的是一種小將軍:

-Scope <String> 
Imports the module only into the specified scope. 

Valid values are: 

-- Global: Available to all commands in the session. Equivalent to the 
Global parameter. 

-- Local: Available only in the current scope. 

By default, the module is imported into the current scope, which could be 
a script or module. 

This parameter is introduced in Windows PowerShell 3.0. 

Required?     false 
Position?     named 
Default value    Current scope 
Accept pipeline input?  false 
Accept wildcard characters? false 

注:上述幫助片段是從V3。 0這是我在我的系統上安裝的。 v2.0的幫助可在http://msdn.microsoft.com/en-us/library/windows/desktop/dd819454.aspx。如果可以的話,我衷心推薦使用PowerShell v3.0,如果僅僅是因爲新的ISE。

+0

+1感謝您的補充細節 – Phil 2012-08-03 19:49:25