'Start sync of Active Directory using SDK or API
I'm trying to centralize all onboarding-related account creation into a single app. When it comes to the on prem AD server and Office 365, I notice an admin was using a powershell script that does something like this:
Invoke-Command -ComputerName $server -ScriptBlock {
Import-Module adsync
Start-ADSyncSyncCycle -PolicyType Delta
}
Is there a way to do the same thing via a C# SDK or a REST API? I can keep the Powershell script if needed, but if there's a set of classes or APIs available I'd prefer that.
Solution 1:[1]
• Yes, you can surely invoke a powershell script through a C# SDK by calling the ‘System.Management.Automation.Powershell’ class in the C# script. To do so, you will have to add this class to the C# program that provides several methods to add commands, parameters, and scripts to the pipeline. You can also invoke the pipeline synchronously by calling an overload of the System.Management.Automation.Powershell.Invoke* method, or asynchronously by calling an overload of the System.Management.Automation.Powershell.Begininvoke* and then the System.Management.Automation.Powershell.Endinvoke* method.
Thus, you can create a script of the said powershell commands in a .ps1 file and ensure that the script is executed by calling the above class. To do so, refer the below example of the C# command to be inserted in the C# program pipeline.
PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();
• Also, please find the below sample C# program to execute the powershell script through it using the above cmdlets to invoke a powershell program. The below C# script invokes the pipeline synchronously by calling the overload of the System.Management.Automation.Powershell.Invoke* method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
namespace HostPS1e
{
class HostPS1e
{
static void Main(string[] args)
{
// Using the PowerShell.Create and AddCommand
// methods, create a command pipeline.
PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();
// Using the PowerShell.Invoke method, run the command
// pipeline using the supplied input.
foreach (PSObject result in ps.Invoke(new int[] { 3, 1, 6, 2, 5, 4 }))
{
Console.WriteLine("{0}", result);
} // End foreach.
} // End Main.
} // End HostPS1e.
}
For more information regarding the above C# class and options regarding invoking a powershell script through a C# program, refer the below Microsoft documentation: -
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KartikBhiwapurkar-MT |
