1

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

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

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

CommandNotFoundException:无法加载模块“Microsoft.Xrm.Data.PowerShell”。有关详细信息,请运行“导入模块 Microsoft.Xrm.Data.PowerShell”。

但是,从 PowerShell ISE 运行相同的测试时,运行没有问题。这似乎好像没有为 Visual Studio 运行的实例安装模块(我在运行时确认了这一点,Get-Module -ListAvailable并看到输出不包含Microsoft.Xrm.Data.PowerShell用于 Visual Studio 测试的模块),尽管即使是像Import-Module Microsoft.Xrm.Data.PowerShell -Global -Forcedon'这样的显式调用t 似乎在使用 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 中运行会受到限制。

4

1 回答 1

1

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

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

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

$Home\Documents\WindowsPowerShell\Modules 

对于系统范围的安装:

$Env:ProgramFiles\WindowsPowerShell\Modules

可以在 MSDN 上找到有关在 PowerShell 中安装模块的进一步阅读。

关于您的实际问题:

您使用的是什么 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 
于 2017-12-16T00:41:56.833 回答