首页 > 解决方案 > 调用命令中的导入模块

问题描述

我正在尝试在 Hyper-V 环境中使用 DHCP 服务器自动设置域控制器。当我尝试安装 DHCP 服务器时出现问题。实际上,当我尝试导入 DhcpServer powershell 模块时。

这是相关代码,其中 DC1 是 vm 的名称:

$Cred = Get-Credential

[scriptblock]$Scriptblock = {
    Write-Host "Install DHCP feature & management tools"
    Install-WindowsFeature dhcp -IncludeManagementTools

    Write-Host "Import DhcpServer module"
    Import-Module DhcpServer # Error happens here
}

$Session = New-PSSession -VMName "DC1" -Credential $Cred
Invoke-Command -Session $Session -ScriptBlock $Scriptblock 

这将使用 powershell direct 在 vm 上安装 DHCP 服务器角色。但是 Import-Module 语句失败并出现以下错误:

Cannot find the Windows PowerShell data file 'DhcpServerMigration.psd1' in directory 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\DhcpServer\en\', or in any parent culture 
directories.
    + CategoryInfo          : ObjectNotFound: (C:\Windows\syst...rMigration.psd1:String) [Import-LocalizedData], PSInvalidOperationException
    + FullyQualifiedErrorId : ImportLocalizedData,Microsoft.PowerShell.Commands.ImportLocalizedData
    + PSComputerName        : DC1

我想指出该文件确实存在C:\Windows\system32\WindowsPowerShell\v1.0\Modules\DhcpServer\en\DhcpServerMigration.psd1另外,当我尝试使用绝对路径导入模块时,我得到了同样的错误。

当我通过执行以下步骤手动执行这些步骤时:

$Cred = Get-Credential
$Session = New-PSSession -VMName "DC1" -Credential $Cred
Enter-PSSession $Session
Install-WindowsFeature dhcp -IncludeManagementTools
Import-Module DhcpServer

一切正常,这是一个成绩单:

PS C:\_repo\> $Session = New-PSSession -VMName "DC1" -Credential $Cred
PS C:\_repo\> Enter-PSSession $session
[DC1]: PS C:\Users\administrator\Documents> Install-WindowsFeature dhcp -IncludeManagementTools

Success Restart Needed Exit Code      Feature Result
------- -------------- ---------      --------------
True    No             Success        {DHCP Server, Remote Server Administration...

[DC1]: PS C:\Users\administrator\Documents> Import-Module DhcpServer

我错过了什么?为什么第一个选项 -invoke-command失败?这两个选项都直接使用 powershell。

在@FSCKur 的建议后更新:

最初的设置是具有文化的主机和具有en-US文化的虚拟机nl-BE。如图所示,Import-Module失败了。

我创建了一个具有en-US文化的新虚拟机。现在Import-Module按预期工作。

Import-Module一个更新的问题是,当与 Invoke-Command cmdlet 一起使用时,当主机和 vm 之间的文化不同时,为什么会失败?

标签: powershellpowershell-remotingimport-module

解决方案


$pso = New-PSSessionOption -Culture "en-US" -UICulture "en-US"
$VM = New-PSSession -ComputerName $vm -Credential $cred -Name VM -SessionOption $pso

推荐阅读