Как вызвать скрипт Powershell с помощью веб-API (cs или asp.net) - PullRequest
0 голосов
/ 04 февраля 2019

Ниже приведена функция для поддержания сервера в режиме обслуживания SCOM, и я хотел бы вызвать эту функцию через cs или asp.net как вызов API, передавая переменные.

function set-scomderegister {    
    param(
        [Parameter( Mandatory = $True,  ValueFromPipeline = $true)][string]
        $SCOMServer,
        [Parameter( Mandatory = $True,  ValueFromPipeline = $true)]
        $Computername
    )

    ForEach($Comp in $Computername)
    {
      New-SCManagementGroupConnection -ComputerName $SCOMServer
      $numberOfMin = 100
      $ReasonComment = "Server got docomissioned "
      $Instance = Get-SCOMClassInstance -Name $Comp 
      $Time = ((Get-Date).AddMinutes($numberOfMin))
      Start-SCOMMaintenanceMode -Instance $Instance -EndTime $Time -Comment $ReasonComment -Reason PlannedOther;    
    }
}

1 Ответ

0 голосов
/ 04 февраля 2019

Пространство имен System.Management.Automation будет полезно для вас.

Вы можете установить пакет nuget "System.Management.Automation".После установки у вас будет доступно это пространство имен.

Вы можете вызвать сценарий с параметром, как показано ниже:

public void RunWithParameters()
{
    // create empty pipeline
    PowerShell ps = PowerShell.Create();

    // add command
    ps.AddCommand("test-path").AddParameter("Path", Environment.CurrentDirectory); ;

    var obj = ps.Invoke();
}

private string RunScript(string scriptText)
{
    // create Powershell runspace

    Runspace runspace = RunspaceFactory.CreateRunspace();

    // open it

    runspace.Open();

    // create a pipeline and feed it the script text

    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);

    // add an extra command to transform the script
    // output objects into nicely formatted strings

    // remove this line to get the actual objects
    // that the script returns. For example, the script

    // "Get-Process" returns a collection
    // of System.Diagnostics.Process instances.

    pipeline.Commands.Add("Out-String");

    // execute the script

    Collection<psobject /> results = pipeline.Invoke();

    // close the runspace

    runspace.Close();

    // convert the script result into a single string

    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }

    return stringBuilder.ToString();
}

Существует еще один вариант использования Process.Start для запуска подсказки powershell.Затем передайте путь к файлу процессу.

public static int RunPowershellScript(string ps)
{
    int errorLevel;
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo("powershell.exe", "-File " + ps);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;

    process = Process.Start(processInfo);
    process.WaitForExit();

    errorLevel = process.ExitCode;
    process.Close();

    return errorLevel;
}

Надеюсь, это поможет.

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