Create Distribution group in Outlook using Microsoft Exchange Online with .Net - c#

I am trying to create a distribution group in Outlook with the help of powershell module ExchangeOnlineManagement I was able to write out the script and it was working fine but When I try to create the same script using .Net and it is giving error
````
using(PowerShell ps = PowerShell.Create(runspace)){
SecureString credential = GetPassword();
ps.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
ps.Invoke();
ps.Commands.Clear();
ps.AddCommand("Connect-ExchangeOnline");
ps.AddParameter("Credential", credential);
Collection<PSObject> results = ps.Invoke();
}
```
I am getting the following error
Unhandled exception. System.Management.Automation.CommandNotFoundException: The term 'Connect-ExchangeOnline' is not recognized as the name of a cmdlet, function, script file, or operable program.
Can anyone help me with this ?

Related

Run PowerShell script from C#

I have a requirement to run a PS file from C#. PS1 file content is $ADStatus=Test-ComputerSecureChannel -Server "xyz.com";.
When I run this PS file from C# I get the following error, however when running the same PS file from a PowerShell window it runs fine. What should I do?
System.Management.Automation.CommandNotFoundException , System.Management.Automation.CommandNotFoundException: The term 'Test-ComputerSecureChannel' is not recognized as a name of a cmdlet, function, script file, or executable program.
I am using package Microsoft.Powershell.SDK v7.1.5.
C# code:
using System.Management.Automation;
using (var ps = PowerShell.Create(string scriptFilePath))
{
var result = ps.Invoke();
var results = ps.AddScript(File.ReadAllText(scriptFilePath)).Invoke();
}

How to fix error "Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly"

I'm trying to execute a Powershell script from an asp.net webpage and I keep getting this error when it tries to execute the script. I have tried 2 methods of executing the script and both give me the same error. The full error is:
An unhandled exception occurred while processing the request
PSSnapInException: Cannot load PowerShell snap-in
Microsoft.PowerShell.Diagnostics because of the following error: Could
not load file or assembly
'C:\source\repos\WebApp\WebApp\Microsoft.PowerShell.Commands'. The
system cannot find the file specified.
PowerShell powershell = PowerShell.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
powershell.Runspace = runspace;
System.IO.StreamReader sr = new System.IO.StreamReader("C:\\Desktop\\test.ps1");
powershell.AddScript(sr.ReadToEnd());
var results = powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
// error records were written to the error stream.
// do something with the items found.
}
}
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("C:\\Users\\RSpotton\\Desktop\\test.ps1");
PowerShellInstance.Invoke();
}
I had a similar issue and accompanying error message. Installing the NuGet package for Microsoft.PowerShell.SDK into my project did the trick.

Run powershell command from C# application

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

Import-Module won't work when launched from .net

I'm trying to run a powershell script within my C# web application.
When i run the following in powershell, it works fine.
Import-Module 'C:\\Program Files\\Microsoft Dynamics NAV\\80\\Service\\NavAdminTool.ps1'
Get-NAVTenant -ServerInstance DynamicsHost
But when i'm running it using my web application, it tells me
The term 'Get-NAVTenant -ServerInstance DynamicsHost' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Here is my c# code:
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "C:\\Program Files\\Microsoft Dynamics NAV\\80\\Service\\NavAdminTool.ps1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-NAVTenant -ServerInstance DynamicsHost");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
Can someone point me in the right direction??
UPDATE:
Using runspace.SessionStateProxy.PSVariable.GetValue("Error") i could see the following error:
Cannot bind argument to parameter 'Name' because it is null.
Cannot bind argument to parameter 'Path' because it is null.
Cannot find path 'HKLM:\SOFTWARE\Microsoft\Microsoft Dynamics NAV\80\Service' because it does not exist.
A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows.
A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows.
A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows.
The error message suggests that your entire command string is interpreted as the name of a (non-existent) cmdlet. According to the documentation the AddCommand() method expects the name of a cmdlet, while parameters should be added via AddParameter().
Try changing this:
ps.Commands.AddCommand("Get-NAVTenant -ServerInstance DynamicsHost");
into this:
ps.Commands.AddCommand("Get-NAVTenant");
ps.Commands.AddParameter("-ServerInstance", "DynamicsHost");
or this:
ps.AddCommand("Get-NAVTenant");
ps.AddParameter("-ServerInstance", "DynamicsHost");
I can verify the following code works, posted from above: the following code will return the DatabaseServer name of the specified Dynamics NAV service tier
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "C:\\Program Files\\Microsoft Dynamics NAV\\80\\Service\\NavAdminTool.ps1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-NAVTenant");
ps.Commands.AddParameter("-ServerInstance", "objectupgrade");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.Properties["DatabaseServer"].Value);
}
Console.Read();
Console.ReadKey();
A better and a much quicker method is to use the Microsoft.Dynamics.Nav.Management snap-in directly. Significant performance improvement can be seen by using this method. Please see following code found here: Why does PowerShell class not load a snapin
var config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("Microsoft.Dynamics.Nav.Management", out warning);
using (Runspace runspace = RunspaceFactory.CreateRunspace(config))
{
runspace.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddCommand("Get-NAVTenant");
ps.AddParameter("ServerInstance", "ObjectUpgrade");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.Properties["DatabaseServer"].Value);
}
Console.Read();
Console.ReadKey();
}
}
It turned out to be that the developer web server could't handle the request. Switching to IIS as developer server solved the problem. Now both of watto's examples works.

The term 'Get-CsUser' is not recognized as the name of a cmdlet, function, script file, or operable program

I am getting below exception if run lync powershell command "Get-CsUser". I am running application with administrator and on machine which have lync powershell.
System.Management.Automation.CommandNotFoundException: The term
'Get-CsUser' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
at
System.Management.Automation.CommandDiscovery.LookupCommandInfo(String
commandName, CommandOrigin commandOrigin) at
System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String
commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at
System.Management.Automation.Runspaces.Command.CreateCommandProcessor(ExecutionContext
executionContext, CommandFactory commandFactory, Boolean addToHistory)
at
System.Management.Automation.Runspaces.LocalPipeline.CreatePipelineProcessor()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
at
System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
sample code:
using (Runspace runspace = RunspaceFactory.CreateRunspace(initial))
{
//// open it
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript("import-module 'C:\\Program Files\\Common Files\\Microsoft
ps.AddCommand("Get-CsUser");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
runspace.Close();
}
}
any suggestion to fix this ???
I don't have an answer, but there is a series of 4 articles that describe using Lync powershell cmdlets and C#. For example, here's a link to one of the articles:
PowerShell Scripting Lync 2010 SDK Using Lync Model API
The full set of four articles is published here:
Lync 2010 Technical Articles

Categories

Resources