How to script azure b2c applications creation - c#

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

Related

Visual Studio can't execute a Powershell script due to execution policy

I'm trying to run a basic powershell script in a c# application, but I can't seem to get it to run. I've tried this code with and without the added execution policy code in the pipeline creation and have gotten the same results.
static void Main(string[] args)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");
pipeline.Commands.Add(#"C:\Users\Bob\Desktop\testScript.ps1");
// Execute PowerShell script
var results = pipeline.Invoke();
}
The error I receive is this:
System.Management.Automation.PSSecurityException: 'File C:\Users\Bob\Desktop\testScript.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.'
When I run "get-executionpolicy -list", my execution policy seems to be fine.
Normally, the persistently configured script execution policy applies to PowerShell SDK-based projects such as yours, too.
While your Get-ExecutionPolicy -List output implies that RemoteSigned is the effective policy (as reported when you omit -List), the color of your screenshots suggest that you were asking for Windows PowerShell's policy, which is separate from the execution policy for the cross-platform, install-on demand PowerShell (Core) v6+ edition.
Therefore, your inability to execute a local script - which RemoteSigned should allow - can have one of two causes:
If you project is based on the SDK for PowerShell (Core) v6+ (via the Microsoft.PowerShell.SDK NuGet package), you'd have to consult - and possibly modify - its effective execution policy (run pwsh -c Get-ExecutionPolicy to see the policy in effect)
If you don't actually have PowerShell (Core) 6+ itself installed (i.e if you're only using its SDK), use the solution in the bottom section - which may be preferable anyway.
As Mathias points out in a comment, another possible reason is that your local script may have been downloaded from the web, via a web browser, in which case it is considered a remote file for the purpose of the execution policy. Passing its file path to Unblock-File as a one-time action should fix the problem.
Taking a step back:
If you trust the local script to invoke, you can bypass the execution policy for your application only, by configuring your PowerShell SDK session accordingly - see this answer.

How to Install SharePoint PowerShell Module inside C# for Azure Function App

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

Using C# to execute Powershell command (azureVM)

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.

Add an Office365 user to the Role Group "View-Only Organization Management"

I am trying to add an Office365 User to the Role-Group, "View-Only Organization Management" from client side using C# and PowerShell. I have installed the Azure AD on my local machine. After which, I am able to run the following cmdlets both from PowerShell as well as my Console app:
Connect-MsolService
New-MsolUser
Add-MSOLRoleMember
Now, to add the User, to the Role-Group, "View-Only Organization Management", I tried to use the cmdlet, Add-RoleGroupMember in the format,
Add-RoleGroupMember "View-Only Organization Management" -Member PK
PK is the display name of the User. But when I execute this cmdlet from PowerShell or my Console app, I am getting the following error:
So how can I achieve this? Thanks in advance.
I figured out that none of the "Exchange 2013" cmdlet will not be present on our machine by default., We need to import the Powershell Session before using the cmdlet and then to remove it when we're done using it. Below is the complete set of commands needed to perform this task:
Open Windows Powershell.
Get the credentials.
$Cred = Get-Credential
Create a remote PowerShell session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $UserCredential -Authentication Basic –AllowRedirection
Plz make sure that the url given above is for Exchange Online only.
Import the cmdlets to the PowerShell
Import-PSSession $Session
Once the import is done, all the Exchange 2013 cmdlets become available.
We can then execute the cmdlet, "Add-RoleGroupMember"
Add-RoleGroupMember -identity "View-Only Organization Management" -member PKS
Finally, don't forget to remove the Session before exiting.
Remove-PSSession $Session
The only difference was that earlier I was not importing the PSSession before executing this cmdlet. Plz note that import is valid for any Exchange 2013 cmdlet and not just for this only.
For further details, you can visit here.

How do I host a Powershell script or app so it's accessible via WSManConnectionInfo? (like Office 365)

The only ways I know to connect to a remote runspace include the following parameters
WSManConnectionInfo connectionInfo =
new WSManConnectionInfo(false, "localhost", 80, "/Powershell", "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
or
WSManConnectionInfo connectionInfo =
new WSManConnectionInfo(false, "localhost", 5985, "/wsman", "http://schemas.microsoft.com/powershell/Microsoft.Powershell", credential);
How do I set up my own custom Powershell object so I can expose it through HTTP?
What are the correct parameters to use and how do I set them up?
There are several pieces to this, so I'll explain them separately and then bring them together.
Implicit Remoting
Exchange is using Implicit Remoting.
The way it works is that you establish a PSSession to a remote machine, then import some of the commands available from the remote instance into your own.
This is done using Import-Module -Session $session or Import-PSSession.
You can try this for yourself purely in Powershell. Use a workstation that does not have the Active Directory RSAT installed (doesn't have the ActiveDirectory powershell cmdlets), then connect to a machine that does (let's call it DC1):
$s = New-PSSession -ComputerName DC1
Invoke-Command -Session $s -ScriptBlock { Import-Module ActiveDirectory }
Import-PSSession -Session $s -Module ActiveDirectory
Restricting the call to Import-PSSession to just the one module lets you import just those cmdlets. At this point you would be able to execute Get-ADComputer for example, as though it were available locally, even though the actual call is being done on DC1.
Session Configurations
When you make a powershell remoting connection, you are connecting to a session configuration. If you don't specify one, you connect to one called Microsoft.PowerShell. To see all of the configurations that are defined on a machine, call Get-PSSessionConfiguration. You might see some others, for example Microsoft.PowerShell32 is a way to connect to a 32 bit powershell session.
To connect to a specific configuration, use New-PSSession -ConfigurationName or New-PSSession -ConnectionUri.
Defining Session Configurations
You can specify a lot of stuff in a session configuration; the version of powershell, the bitness, which modules are pre-imported, you can pre-define functions and code, you can prevent language features from being available, etc.
This answer provides a good overview of how to create your own configuration.
You can also put configuration information inside of an assembly, which would work well for what you're trying to do.
Wrapping Code in Modules
As you've seen with Import-PSSession it's easier to import just the code you want if it exists in a module. Therefore you should make sure that your cmdlet is exposed through a module.
You said in a comment that you wanted to write your cmdlet in C#. This is not something I've done, but this article appears to provide detailed instructions on how to create a PowerShell Module in C#.
This is now something I have done (and that article is good). Writing a cmdlet in C# is, implicitly, already a module. In fact, you can use Import-Module to load a compiled .NET assembly, whether it contains any PowerShell cmdlets or not.
For example if you created a public class and compiled it into a DLL, you can do Import-Module MyAssembly.dll and that class is now available in your PowerShell session.
Defining the cmdlet in C# means including a reference to System.management.Automation and then creating a class that inherits from Cmdlet or PSCmdlet.
Defining the module manifest is recommended but technically optional, just as it is with a script module.
I have not however included the session configuration information in an assembly (yet?), nor have I seen a reference for how to do that.
Bringing it Together
The steps should roughly resemble this:
Compile module and make it available on the remote end, so that it can be imported to powershell from a local session on that machine.
Create a new PSSession configuration file, and specify either -AssembliesToLoad or -ModulesToImport (or both if necessary), or specify the configuration information in the assembly itself (probably preferred here).
Register the configuration on the machine.
On the client side, you wanted to make it available to PowerShell, so you would simply create the session, then import it:
$s = New-PSSession -ComputerName RemoteMachine -ConfigurationName MyConfig
# The configuration was defined in such a way
# that your module will already be imported in the remote session.
Import-PSSession -Module MyModule
Simplifying it?
You don't have to create a custom configuration on the remote side. As long as your module is available to any powershell session on the remote machine, you can skip the session configuration steps, and then you would just do:
$s = New-PSSession -ComputerName RemoteMachine
Invoke-Command -Session $s -ScriptBlock { Import-Module MyModule }
Import-PSSession -Session $s -Module MyModule
But you may want the additional customization and control you have by using a session configuration, so that's up to you. That's how exchange does it, but it may be overkill for your purposes.

Categories

Resources