简体   繁体   中英

Make PowerShell script run cmdlets in global scope

I have written the following PowerShell script:

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

The only problem with this script is that Import-Module only applies inside that script's scope - it does not import the module in the global scope. Is there any way to make a script import a module so that it stays around after the script finishes?

Note: dot-sourcing like so: . Reload-Module MyModuleName . Reload-Module MyModuleName does not work.

From the Powershell help:

-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 also adds the -Scope parameter, which is a little more general:

-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

Note: the above help snippets are from v3.0 which is what I have installed on my system. The v2.0 help is available at http://msdn.microsoft.com/en-us/library/windows/desktop/dd819454.aspx . I'd heartily recommend getting PowerShell v3.0 if you can, if only because of the new ISE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM