Using C# to execute Powershell command (azureVM)

12,696

Solution 1

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.Automation
System.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 class
using (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!

Solution 2

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.

Share:
12,696
mlaribi
Author by

mlaribi

.Net/Core, VueJs, MSSQL and exploring everything interesting programming

Updated on June 04, 2022

Comments

  • mlaribi
    mlaribi almost 2 years

    I'm trying to develop a .Net form application to manage azure VMs in C# using Powershell cmdlets. I'll have to use the Azure module to get this working.

    One of the cmdlet will be Add-AzureAccount

    My question is how can I include this module (Azure) in C# project ?