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 ?
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!
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.
Related
I need to create bunch of azure b2c application with powershell scripts.
A powershell script to perform steps described here
https://learn.microsoft.com/it-it/azure/active-directory-b2c/tutorial-register-applications
thank you
Currently, it is only possible to manage B2C policies programmatically. Since B2C Custom Policies went GA, it is now possible to create custom policies using PowerShell.
Refer this: https://stackoverflow.com/a/56252795/10571855
However, the feature request for programmatic app mgmt is here. Please vote for it so that we can let you know when it is available for preview.
You can use PowerShell AzureADPreview 2.0 module to create applications.
Full doc is here: AzureADPreview 2 docs
I had no success to install this module to "old" PowerShell (5.x) so I gave a shot to the 'new' PowerShell 7 (Core). The only issue with PowerShell 7 and AzureAD module is that Connect-AzureAD uses a cryptographic function which is not in .NET Core, so you must import the AzureADPreview module using the -UseWindowsPowerShell option.
Here is a sample, works with PowerShell 7:
Install-Module AzureADPreview
Import-Module AzureADPreview -UseWindowsPowerShell
$tenantId = "yourb2ctenant.onmicrosoft.com"
# Note: this will interactively ask your credentials.
# If you want to run this unattended, use the -Credential parameter with a PSCredential object with a SecureString
Connect-AzureAD -TenantId $tenantId
# ready to go
#list your all apps
Get-AzureADApplication
# examine one of you app and get ideas
$application = Get-AzureADApplication -ObjectId af46a788-8e55-4301-b2df-xxxxxxxxx
# create and application
$applicationName = "yourappname"
$application = New-AzureADApplication -DisplayName $applicationName -PublicClient $true etc
I would like to run the following powershell commands from my C# application:
Enter-PSSession –ComputerName fedsrv01.domain.local
Start-ADSyncSyncCycle -PolicyType Delta
I found some information on the Powershell Class but struggling to achieve what I want due to my lack of experience.
https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?redirectedfrom=MSDN&view=pscore-6.2.0
This is what I have so far:
I have added the assembly and referenced system.management.automation
using (var powershell = PowerShell.Create())
{
//powershell.AddCommand("get-process");
powershell.AddCommand("Enter-PSSession -ComputerName fedsrv01.domain.local");
powershell.Invoke();
}
I get an error saying, 'The term 'Enter-PSSession -ComputerName fedsrv01.domain.local' is not recognized as the name of a cmdlet, function, script file, or operable program.
if I use: powershell.AddCommand("get-process") it executes fine.
If I launch Powershell on the same PC and enter, Enter-PSSession -ComputerName fedsrv01.domain.local it works fine.
Any assistance would be much appreciated.
Cheers,
Jono
Try compiling your application as x64. If it is compiled as x86 platform then it will be using the virtualized System32 dir so the function you require may not exist.
Powershell commands from C# 'the term is not recognizes as cmdlet'
Ok, after more research into the PowerShell class I now realise that you have to add the parameters separately using the .addparameter method.
.addcommand is just for the PowerShell commands. It now makes sense why I got the error saying the command could not be found. It was assuming the entire string was a command.
Problem solved!
Jono
Just to manage expectations, I am new to PowerShell and to Azure Functions.
Since Azure Functions 2.x no longer supports PowerShell so I am trying to run my PowerShell scripts which requires SPO modules from C# (code below) I am having trouble running the Azure Function App because the PowerShell scripts needed the SPO modules. Anybody who knows how to install the needed modules inside C# PowerShell Instance like Runspace or anything the like? I am even on the right track here? Any comments is highly appreciated. Thank you all.
Sample Code:
[FunctionName("TestFunction")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
var script = #"
Install-Module Microsoft.Online.SharePoint.PowerShell
Install-Module SharePointPnPPowerShellOnline
$url = '<SharePoint Url>'
$ListName = '<List Name>'
Connect-PnPOnline -Url $url -UseWebLogin
$Fields = Get-PnPField -List $ListName
$Items= Get-PnPListItem -List $ListName -PageSize 5000
$RowCtr = 1;
foreach($item in $items.FieldValues)
{
#do something
$RowCtr++;
}
";
PowerShellInstance.AddScript(script);
var results = PowerShellInstance.Invoke();
//some other codes
}
}
You can use Runspace within an Azure Function as shown in this example, lines 93-98. For modules, you can include them as part of the payload you deploy to your function app (recommended), or install them using Kudu.
Once you upload your modules via the payload or Kudo, your script should work with a few modifications. The modules can be directly downloaded from the https://www.powershellgallery.com/ using Save-Module.
After that, your script should work with a few modifications. According to https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/connect-pnponline?view=sharepoint-ps, -UseWebLogin is browser based. Alternatively, you can use the -Credentials parameter. Here is how you build a PSCredential object:
$secPassword = ConvertTo-SecureString "StringPassword" -AsPlainText -Force
$credential = [System.Management.Automation.PSCredential]::new("userName", $secPasswd)
Update on 1/23/20:
As of November 2019, PowerShell in Functions has GA-ed and it is available in Functions V2 and V3, for more information, please visit https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell
To have your PowerShell function app install dependencies from the https://www.powershellgallery.com/, you can use our managed dependencies feature. For more info, please visit https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-powershell#dependency-management.
Cheers,
Francisco
I am trying to automate the running of a powershell script along with the running of other programs.
To run the powershell script manually, I would normally do this in a command prompt:
powershell "IEX (New-Object Net.WebClient).DownloadString('http://serverurl/Script.ps1'); Invoke-Method"
I can't seem to replicate this in c# to save my life using built in "PowerShell" commands. I"d rather NOT have to use things like "Process", so any advice would be helpful.
Since System.Net.WebClient is a .NET class, you don't need PowerShell to use it:
string script = (new System.Net.WebClient()).DownloadString('http://serverurl/Script.ps1');
To execute the script, use the System.Management.Automation.PowerShell class:
using System.Management.Automation;
// ...
using(PowerShell ps = PowerShell.Create())
{
ps.AddScript(script).AddScript("Invoke-Method");
ps.Invoke();
}
I'm using System.Management.Automation.PowerShell to programmatically execute a PowerShell script from C# application. The PowerShell script loads a .Net dll which it uses to perform its activities.
var script = "Add-Type -Path 'MyLibrary.dll'; ....";
using (var powershell = PowerShell.Create()) {
powershell.AddScript(script);
powershell.Invoke();
}
Is it possible to somehow connect Visual Studio's debugger to the PowerShell object instance so that the debugger can seamlessly step from the C# application into the PowerShell script and from that script into MyLibrary.dll (assuming I have symbols for the dll)?
Edit: Based on the below, it appears that there may not be a way to seamlessly flow debugging in Visual Studio from C# to PowerShell. However, it is possible to use VS to debug the C# code that launches and that is launched by PowerShell.
You could debug the dll file by calling the following in your helper class:
System.Diagnostics.Debugger.Launch();