【发布时间】:2017-06-28 12:43:28
【问题描述】:
我正在尝试从 Windows 服务项目(.net 框架 2.0)调用 Powershell 命令Get-DSCLocalConfigurationManager。 using System.Management.Automation
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
try
{
runspace.Open();
var ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddCommand("Get-DSCLocalConfigurationManager");
var results = ps.Invoke();
foreach (PSObject result in ps.Invoke())
{
_eventLog.WriteEntry(result.Members["AgentId"].Value.ToString());
}
}
catch (Exception e)
{
_eventLog.WriteEntry($"Powershell Command failed with: {e.Message}", EventLogEntryType.Error);
}
}
在 powershell 窗口中调用命令按预期工作。
问题在于,我尝试以这种方式调用的几乎每个命令都会返回异常:
“‘Get-DSCLocalConfigurationManager’ 一词未被识别为 cmdlet 的名称,...”
我尝试了命令Get-Module -ListAvailable$PSVersionTable.PSVersion,结果相同。有些命令类似于Get-Process,所以我假设缺少模块。
导入模块并像这样调用命令
ps.AddScript(@"Import -Module 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1'; Get-DSCLocalConfigurationManager");
也不起作用,因为它返回以下错误:
无法导入“C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1”模块,因为其清单包含一个或多个无效成员。有效的清单成员是 ('ModuleToProcess', 'NestedModules', 'GUID', 'Author', 'CompanyName', 'Copyright', 'ModuleVersion', 'Description', 'PowerShellVersion', 'PowerShellHostName', 'PowerShellHostVersion', 'CLRVersion'、'DotNetFrameworkVersion'、'ProcessorArchitecture'、'RequiredModules'、'TypesToProcess'、'FormatsToProcess'、'ScriptsToProcess'、'PrivateData'、'RequiredAssemblies'、'ModuleList'、'FileList'、'FunctionsToExport'、'VariablesToExport '、'AliasesToExport'、'CmdletsToExport')。删除无效的成员('DscResourcesToExport'、'HelpInfoURI'),然后再次尝试导入模块。
调用这样的命令时使用什么 Powershell 版本?它是与我正在使用的 .net 框架版本相关联,还是系统的已安装版本?加载了哪些模块?我该怎么做才能调用这个命令?
编辑:我创建了一个简单的控制台应用程序,发现它与框架版本有关。使用 .net framework 4.0 可以按预期工作,但是一旦我使用 3.5 或更低版本,我描述的问题就会出现。
【问题讨论】:
标签: c# .net powershell windows-services .net-2.0