powershell - 调用命令中的导入模块
问题描述
我正在尝试在 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 之间的文化不同时,为什么会失败?
解决方案
$pso = New-PSSessionOption -Culture "en-US" -UICulture "en-US"
$VM = New-PSSession -ComputerName $vm -Credential $cred -Name VM -SessionOption $pso
推荐阅读
- swift - 尝试使用 Active Label 作为标题时崩溃
- javascript - Getting mutual friends MongoDB
- sql - 如何获取字符串中特定字符的所有位置索引?
- c - 无法让 Uno32 以预期的频率运行定时器 1 中断
- ansible - 获取清单主机名列表
- jquery - 如何从jquery中已经打开的窗口打开一个新窗口?
- javascript - 如何让 promise.response 返回 API 的响应?
- html - 在 .py 文件中编写 html 代码的格式是什么?
- javascript - 在 vue.js 中,我如何为需要 js 库的组件提供服务?
- c# - 如何在 STA 线程中运行 NUnit 测试?