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

时间:2017-12-15 22:56:25

标签: powershell visual-studio-2015 pester

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

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

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

  

CommandNotFoundException:模块' Microsoft.Xrm.Data.PowerShell'无法加载。有关更多信息,请运行“导入 - 模块Microsoft.Xrm.Data.PowerShell'。

从PowerShell ISE运行时的相同测试运行没有问题。这似乎就像Visual Studio运行的实例没有安装模块一样(我在运行Get-Module -ListAvailable时确认了这一点并且看到输出不包含Visual Studio的Microsoft.Xrm.Data.PowerShell模块测试),尽管像Import-Module Microsoft.Xrm.Data.PowerShell -Global -Force这样的显式调用似乎不会在使用Visual Studio执行脚本期间加载模块。

此处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而不是实际尝试创建/读取记录,但是无法加载外部模块并在Visual Studio中运行会受到限制。

1 个答案:

答案 0 :(得分:1)

关于模块安装目录(如果您对实际问题感兴趣,请跳过此步骤):

首先,您永远不应该将模块安装到$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中。

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

PS> [Environment]::Is64BitProcess
True

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

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