如何使用Web API(CS或ASP.NET)调用Powershell脚本

时间:2019-02-04 20:15:56

标签: c# asp.net powershell

以下是使服务器保持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 :(得分:1)

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;
}

希望这会有所帮助。