在 Visual Studio 中进行 运行 Pester 测试时无法加载 PowerShell 模块

PowerShell Module cannot be loaded when running Pester test in Visual Studio

我创建了一个 PowerShell 测试脚本,Common.tests.ps1,使用 Pester 对 PowerShell 脚本中的一些函数,Common.ps1,在同一目录中。

有一个 TestInitializer.ps1 脚本,也在同一目录中,它使用 Microsoft.Xrm.Data.PowerShell 模块在 Dynamics CRM 实例中创建和获取记录。

当 运行从 Visual Studio 运行 PowerShell 测试脚本时,测试在测试资源管理器中失败并显示消息:

CommandNotFoundException: The module 'Microsoft.Xrm.Data.PowerShell' could not be loaded. For more information, run 'Import-Module Microsoft.Xrm.Data.PowerShell'.

来自 PowerShell ISE 的 运行 时的相同测试,但是,运行 没有问题。这似乎好像 Visual Studio 没有为实例安装模块 运行 (我在 运行ning Get-Module -ListAvailable 时确认了这一点,看到输出没有包括用于 Visual Studio 测试的 Microsoft.Xrm.Data.PowerShell 模块),尽管在使用 Visual Studio.[=25 执行脚本期间,即使像 Import-Module Microsoft.Xrm.Data.PowerShell -Global -Force 这样的显式调用似乎也不会加载模块=]

这是Common.test.ps1

$here = (Split-Path -Parent $MyInvocation.MyCommand.Path)
. $here\Common.ps1
. $here\TestInitializer.ps1

Describe "SelectionToSingleCharString" {
Context "StringTransforms" {
    It "Retrieves a CRM record and uses the optionset value to retrieve a single character" {
    SelectionToSingleCharString($crmRecord.new_type) | Should Be "I"
        }
    }
}

来自 TestInitializer.ps1 的片段:

# Whether or not this is uncommented does not matter
#Import-Module "$env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules\Microsoft.Xrm.Data.PowerShell\Microsoft.Xrm.Data.PowerShell.psd1" -Global -Force

#$modules = Get-Module -ListAvailable
#Write-Host $modules

# Failing here
Microsoft.Xrm.Data.PowerShell\Connect-CrmOnPremDiscovery -ServerUrl $loginServerUrl -OrganizationName $loginOrgName -Credential $cred

我可能会将测试设计为使用 Mock 而不是实际尝试 create/read 记录,尽管无法加载外部模块并且 Visual Studio 中的 运行 会受到限制。

关于模块安装目录(对实际问题感兴趣的可以跳过):

首先你不应该安装模块到 $PSHome\Modules (%Windir%\System32\WindowsPowerShell\v1.0\Modules)。此文件夹仅供 Windows 附带的模块使用。

您应该始终将仅供您的用户使用的模块安装在以下路径下:

$Home\Documents\WindowsPowerShell\Modules 

并且在以下系统范围内安装:

$Env:ProgramFiles\WindowsPowerShell\Modules

有关在 PowerShell 中安装模块的进一步阅读可以是 found on MSDN

关于您的实际问题:

您使用的 Visual Studio 版本是什么?我安装了 Visual Studio 2017 社区版,无法重现您的错误。我的 PowerShell 也是 运行 作为 64 位进程。您的 PowerShell 可以 运行 作为 32 位进程。对于 32 位 PowerShell,模块目录不同。这可以解释为什么您安装的模块没有出现在 Visual Studio.

您可以使用以下命令在 64 位进程中验证您的 PowerShell 是否 运行:

PS> [Environment]::Is64BitProcess
True

要让 32 位 PowerShell 可以访问您的模块,您还需要将它们安装在以下路径下:

{$Env:ProgramFiles(x86)}\WindowsPowerShell\Modules