从.net framework 2.0 / 3.5项目调用Powershell Command

问题描述 投票:1回答:1

我正在尝试从Windows服务项目(.net framework 2.0)调用Powershell Command Get-DSCLocalConfigurationManagerusing 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
1个回答
0
投票

我有同样的问题。

它来自Powershell的版本。当您使用System.Management.Automation.dll版本1.0.0.0将项目定位到.Net 2.0 / 3.5时,运行Powershell 2.0,但当您的项目目标为.Net 4+时,使用dll版本3.0.0.0并运行Powershell 3.0 。

我传递给我的运行时Powershell命令来调用shell Powershell并执行命令,如下所示:

var results = powerShell.AddScript("powershell Get-AppxPackage -allusers -name 'Microsoft.WindowsStore'").Invoke();
if (powerShell.Streams.Error.Any())
{
   foreach (var errorRecord in powerShell.Streams.Error)
      throw new Exception();
}

被称为Ppowershell将流重定向到运行时Powershell。

© www.soinside.com 2019 - 2024. All rights reserved.