Выполните команду PowerShell с помощью C # (Windows-приложение .NET) - PullRequest
0 голосов
/ 09 апреля 2019

Я хочу выполнить эту команду PowerShell:

Add-PrinterPort -Name "MyLocalPort:"

Я добавил пакет NuGet для «Management.Automation».В частности, я использую:

System.Management.Automation
System.Collections.ObjectModel

Я видел в предыдущем примере пример кода:

//The first step is to create a new instance of the PowerShell class
using (PowerShell powerShellInstance = PowerShell.Create()) //PowerShell.Create() creates an empty PowerShell pipeline for us to use for execution.
{   
 // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
 // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.

    powerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; $d; $s; $param1; get-service");

    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
    powerShellInstance.AddParameter("param1", "parameter 1 value!");

    //Result of the script with Invoke()
    Collection<PSObject> result = powerShellInstance.Invoke();

    //output example : @{yourProperty=value; yourProperty1=value1; yourProperty2=StoppedDeallocated; PowerState=Stopped; OperationStatus=OK}}

    foreach (PSObject r in result)
    {
        //access to values
        string r1 = r.Properties["yourProperty"].Value.ToString();
    }
}

, но когда я его использовал, я получил эту ошибку:

Error CS0012 The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. 

После некоторых исследований я прочитал, что, возможно, мне не хватает ссылки на пакет NETStandard.Library.NETFramework.Я пытался скачать его с NuGet с здесь , но я получаю эту ошибку:

Install-Package : Could not install package 'NETStandard.Library.NETFramework 2.0.0-preview1-25305-02'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the p
ackage does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
+ Install-Package NETStandard.Library.NETFramework -Version 2.0.0-previ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

Есть идеи, чтобы преодолеть это препятствие?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...