Using C# to execute Powershell command (azureVM) Using C# to execute Powershell command (azureVM) azure azure

Using C# to execute Powershell command (azureVM)


In the comment section, @Prageeth Saravanan gave a useful link on how integrate PowerShell in C#.

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

Quick example :

First I had to include these refs :

System.Management.AutomationSystem.Collections.ObjectModel

Note : You need to add a NuGet package for "Management.Automation". Just type "System.Management.Automation" you'll find it.

C# code:

//The first step is to create a new instance of the PowerShell classusing (PowerShell powerShellInstance = PowerShell.Create()) //PowerShell.Create() creates an empty PowerShell pipeline for us to use for execution.{    // use "AddScript" to add the contents of a script file to the end of the execution pipeline. // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.    powerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; $d; $s; $param1; get-service");    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.    powerShellInstance.AddParameter("param1", "parameter 1 value!");    //Result of the script with Invoke()    Collection<PSObject> result = powerShellInstance.Invoke();    //output example : @{yourProperty=value; yourProperty1=value1; yourProperty2=StoppedDeallocated; PowerState=Stopped; OperationStatus=OK}}    foreach (PSObject r in result)    {        //access to values        string r1 = r.Properties["yourProperty"].Value.ToString();    }}

Hope this helps!


We could use PowerShell cmdlets Import-module to add corresponding modules to the current session. We could use force parameter to re-import a module into the same session.
Import-module -name azure -force

The import thing is that the imported module need to be installed on the local computer or a remote computer. So if we want to execute Azure PowerShell cmdlets from C# project that we need to make sure that Azure PowerShell are installed. We can use install-module AzureRM or Azure more details please refer to the Get Started Azure PowerShell cmdlets. In the Azure VM, Azure PowerShell is installed by default. About how to call PowerShell command or PS1 file using C# please refer to Prageeth Saravanan mentioned link or another SO Thread.