How to run powershell commands in C#
By FoxLearn 2/20/2024 2:01:01 AM 100
You can run PowerShell commands in c# .net by using the System.Management.Automation namespace, which provides classes for interacting with PowerShell from managed code.
Here's a basic example of how you can execute PowerShell commands in C#
using System; using System.Management.Automation; class Program { static void Main(string[] args) { // Create an instance of PowerShell using (PowerShell PowerShellInstance = PowerShell.Create()) { // Add the script/command you want to run PowerShellInstance.AddScript("Get-Process"); // Invoke the command asynchronously. var asyncResult = PowerShellInstance.BeginInvoke(); // Wait for the command to complete while (!asyncResult.IsCompleted) { Console.WriteLine("Waiting for PowerShell to finish..."); System.Threading.Thread.Sleep(1000); } Console.WriteLine("Command completed."); // Get the results of the command foreach (PSObject result in PowerShellInstance.EndInvoke(asyncResult)) { Console.WriteLine(result.ToString()); } } Console.ReadLine(); } }
1. We create an instance of PowerShell
.
2. We add the PowerShell command or script using the AddScript
method.
3. We invoke the command asynchronously using BeginInvoke
.
4. We wait for the command to complete by checking the IsCompleted
property.
Once the command is completed, we retrieve the results using EndInvoke
.
Finally, we display the results in the console.
You can replace "Get-Process"
with any PowerShell command or script you want to execute. Make sure to handle errors and exceptions appropriately in your production code.
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024
What Are RESTful Web Services?
02/19/2024