2

Below is the function to keep server in SCOM maintenance mode and I would like to call this function through cs or asp.net as API call by passing variables.

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;    
    }
}
Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
Jack
  • 35
  • 1
  • 5
  • Maybe useful/what you're looking for: [To Call A Powershell script file C#](https://stackoverflow.com/questions/20195392/to-call-a-powershell-script-file-example-ps1-from-c-sharp) – Jaskier Feb 04 '19 at 20:31

1 Answers1

6

System.Management.Automation namespace would be useful for you.

You can install a nuget package "System.Management.Automation". Once this is installed you will have this namespace available.

You can invoke a script with parameter as shown below:

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

There is another option to use Process.Start to start the powershell prompt. Then pass the file path to the process.

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

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
  • System.Management.Automation namespace looks like good approach, can you please give any examples if you got and also I would like to pass attributes to powershell script. – Jack Feb 05 '19 at 17:49
  • Refer this MSDN link for more details : https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?view=powershellsdk-1.1.0 – Manoj Choudhari Feb 05 '19 at 19:56
  • I also have updated the example in the question. I have executed this on my machine and it works ! Hope this works for you. – Manoj Choudhari Feb 05 '19 at 21:40
  • Thanks a lot for response actually I have one more ques. I am developing web api and below is my post method code and C# script is in MaintennceModeService class but how to call that service by passing arguments that are provided in post. public string Post([FromBody]MaintenanceMode value) { string mgmtserver = value.mgmtserver; string NodeName = value.NodeName; } return MaintennceModeService(value); – Jack Feb 19 '19 at 20:03
  • @Jack - i would suggest to mark this as answer (if this post really helped you to resolve your issue). Then please add another question as it would be very difficult to read teh code from comments. I would be happy to help. – Manoj Choudhari Feb 19 '19 at 20:21
  • https://stackoverflow.com/questions/54776556/how-to-call-power-shell-script-file-by-passing-attributes-in-c-sharp , created new post as you suggested – Jack Feb 20 '19 at 03:08