使 PowerShell 脚本在全局范围内运行 cmdlet [英] Make PowerShell script run cmdlets in global scope

查看:78
本文介绍了使 PowerShell 脚本在全局范围内运行 cmdlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下 PowerShell 脚本:

I have written the following PowerShell script:

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

此脚本的唯一问题是 Import-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?

注意:像这样的点采购:.重新加载模块 MyModuleName 不起作用.

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

推荐答案

来自 Powershell 帮助:

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 还增加了 -Scope 参数,更通用一点:

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

注意:以上帮助片段来自 v3.0,这是我在我的系统上安装的.v2.0 帮助位于 http://msdn.microsoft.com/en-us/library/windows/desktop/dd819454.aspx.如果可以的话,我衷心建议您使用 PowerShell v3.0,哪怕只是因为有了新的 ISE.

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.

这篇关于使 PowerShell 脚本在全局范围内运行 cmdlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆