2012-08-03 47 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