【问题标题】:PowerShell Modules and SnapInsPowerShell 模块和管理单元
【发布时间】:2013-01-30 21:38:55
【问题描述】:

我创建了几个实用程序模块,它们都依赖于 Microsoft.SharePoint.PowerShell 管理单元。

当在我的机器上运行时,脚本全部正确运行,我的配置文件中没有任何模块或管理单元用于 powershell “默认加载”,但是在其他机器上,它们的配置文件不能保证是干净的。

在我的模块加载器 .psd1 文件中,我正在使用以下内容

NestedModules = @( 'Microsoft.SharePoint.PowerShell',
        '.\Modules\CustomModule.psd1')

我使用 ps1 文件来触发这些包含以下 Import Module 命令的模块导入

Import-Module -Name "$dir\.\CustomModules.psd1" -Global -Force -PassThru

如果我以这种方式运行,我会在配置文件包含 Microsoft.SharePoint.PowerShell 管理单元的计算机上出现名称冲突错误,因为该管理单元已被加载。

我知道我们可以使用 -NoProfile 参数执行 PowerShell 命令,但这在我们的场景中不是有效的解决方案。

我还尝试从 NestedModules 部分删除管理单元并在导入模块之前在 .ps1 文件中运行以下命令,但管理单元未显示为已加载,因此模块导入失败。

if ((Get-PSSnapin | ? {$_.Name -eq 'Microsoft.SharePoint.PowerShell'}) -eq $null)
{
    Write-Host "Adding PSSnapin 'Microsoft.SharePoint.PowerShell'"
    Add-PSSnapin 'Microsoft.SharePoint.PowerShell'  }

如何重新设计此解决方案以确保管理单元能够正确加载,并且无论用户配置文件如何,模块都能成功导入?

我的理想情况如下:

Task.ps1   (The custom task me or other devs are trying to achieve)
     > Calls ImportModules.ps1   (Hides the importing logic of modules and snap-ins)
           > Imports CustomModules.psd1  (Imports all modules, functions, global vars into the runspace)

【问题讨论】:

  • 当我将它添加到我的嵌套模块“Microsoft.SharePoint.PowerShell”时,我会立即收到错误消息。我有空的个人资料。这行得通吗?

标签: powershell module pssnapin


【解决方案1】:

我不会让 PSD1 文件通过 NestedModules 加载 snappin。创建一个 CustomModules.psm1 文件并将 ModuleToProcess(或 v3 中的 RootModule)设置为“CustomModules.psm1”。从 NestedModules 中删除 SharePoint dll。然后将类似这样的内容添加到您的 CustomModules.psm1 文件中:

function AddSnapin
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Name
    )

    Process {
        foreach ($n in $name)
        {
            if (!(Get-PSSnapin $n -ErrorAction SilentlyContinue)) {
                Add-PSSnapin $n
            }
            else {
                Write-Verbose "Skipping $n, already loaded."
            }
        }
    }
}

AddSnapin Microsoft.SharePoint.PowerShell -Verbose

【讨论】:

  • 这就是我最终要做的。我还添加的唯一内容是检查是否使用以下约定注册管理单元 get-pssnapin $snapInName -registered 感谢您的帮助!
【解决方案2】:

您可以测试程序集名称的存在

$assemblyname = "Microsoft.SharePoint.PowerShell"
if (([appdomain]::currentdomain.getassemblies() | 
      Where {$_ -match $AssemblyName}) -eq $null )
{
  add-pssnapin Add-PSSnapin 'Microsoft.SharePoint.PowerShell'
}

或者直接加载它,如果已经加载则忽略错误:

Add-PSSnapin -Name "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

【讨论】:

  • 上面的答案会起作用,但问题更多是关于使用模块加载管理单元,而不仅仅是一般如何加载管理单元。
猜你喜欢
  • 2013-07-16
  • 2017-08-21
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多