【问题标题】:Invoke Powershell Command from .net framework 2.0 / 3.5 project从 .net framework 2.0 / 3.5 项目调用 Powershell 命令
【发布时间】:2017-06-28 12:43:28
【问题描述】:

我正在尝试从 Windows 服务项目(.net 框架 2.0)调用 Powershell 命令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】:

    我有同样的问题。

    它来自 Powershell 版本。 当您将项目定位到 .Net 2.0/3.5 时,您使用 System.Management.Automation.dll 版本 1.0.0.0,运行 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。

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 2011-08-31
      • 2017-06-03
      • 1970-01-01
      • 2010-11-01
      • 2010-09-13
      • 2010-10-15
      • 2011-06-28
      • 1970-01-01
      相关资源
      最近更新 更多