Powershell remote commandlet from c# for cim-session - c#

using (PowerShell pInst=PowerShell.Create()) // implements Idisposable
{
string username = Console.ReadLine();
System.Security.SecureString pwd = getPassword();
PSCredential credential = new PSCredential(username, pwd);
pInst.Runspace.SessionStateProxy.SetVariable("cred", credential);
//pInst.AddScript("$cred;");
//pInst.AddScript("$session= New-CimSession -ComputerName anksahawin8a $cred");
//pInst.AddScript("$session;");
//pInst.AddScript("param($param1) $d = get-date;"+"$d; $s; $param1; get-service");
//.AddParameter("param1","Ankit");
//pInst.Invoke(); // Synchronous Invocation
pInst.AddScript("$session= New-CimSession -ComputerName anksahawin8a -Credential $cred;");
//psOutput = pInst.Invoke();
pInst.AddScript("$session;");
Collection<PSObject> psOutput = pInst.Invoke();
//psOutput = pInst.Invoke();
if(pInst.Streams.Error.Count>0) // Errors
{
}
foreach(PSObject pso in psOutput)
{
Console.WriteLine(pso);
if (pso != null)
{
//String result=pso.Members["Value"].Value.ToString();
Console.WriteLine(pso.BaseObject.GetType().FullName);
Console.WriteLine(pso.BaseObject.ToString() + "\n");
}
}
Console.WriteLine("Hello");
}
This code is not working. Whereas
pInst.AddScript("$session= New-CimSession");
for local computer works...

Related

Using PowerShell to Read Office 365 Group Members in C#

I'm attempting to connect to an Office 365 Group and list the membership of the Group using Powershell through a C# Project.
From this article, I've determined the command I need to use is
Get-UnifiedGroupLinks –Identity groupalias –LinkType Members
Here is my current code:
string connectionUri = "https://outlook.office365.com/powershell-liveid/";
SecureString secpassword = new SecureString();
foreach (char c in Password)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(UserName, secpassword);
Runspace runspace = RunspaceFactory.CreateRunspace();
PSObject SessionHolder = null;
using (PowerShell powershell = PowerShell.Create())
{
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;
runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
{
throw new Exception("Fail to establish the connection");
}
else
SessionHolder = result[0];
}
using (PowerShell powershell = PowerShell.Create())
{
PSCommand command = new PSCommand();
// –Identity groupalias –LinkType Members
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-UnifiedGroupLinks"));
command.AddParameter("Session", SessionHolder);
command.AddParameter("Identity", groupAddress);
command.AddParameter("LinkType", "Members");
powershell.Commands = command;
powershell.Runspace = runspace;
Collection<PSObject> PSOutput = powershell.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
}
}
Variables used above, declaration not shown: "UserName", "Password", "groupAddress"
I am able to make a connection to the service, but when I try to get the group members I get the error "A parameter cannot be found that matches parameter name 'Identity'"
I'm not sure how to proceed in troubleshooting my code. I've tried the Group email, Group Alias, and Group Display Name in the Identity parameter. Perhaps I have something else wrong?
I'm using the following Libraries in Visual Studio 2017 on a Windows 10 machine:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
Usually I get that error when I'm passing the variable with some extra characters. Check how the variable is being passed, if its just "email" or if it contains other info like #{"email"}. Very common in Powershell.
Hope that sheds some light. Because the command is very simple:
Get-UnifiedGroupLinks -Identity [name] -LinkType members
I found a bit of code that makes things work... It slows it down, so I'm not sure if there is a better way, but here is my updated code:
string connectionUri = "https://outlook.office365.com/powershell-liveid/";
SecureString secpassword = new SecureString();
foreach (char c in Password)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(UserName, secpassword);
Runspace runspace = RunspaceFactory.CreateRunspace();
PSObject SessionHolder = null;
using (PowerShell powershell = PowerShell.Create())
{
string connectionUri = "https://outlook.office365.com/powershell-liveid/";
SecureString secpassword = new SecureString();
foreach (char c in Password)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(UserName, secpassword);
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri(connectionUri));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");
powershell.Commands = command;
runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
if (powershell.Streams.Error.Count > 0 || result.Count != 1)
throw new Exception("Fail to establish the connection");
else
SessionHolder = result[0];
PSCommand ImportSession = new PSCommand();
ImportSession.AddCommand("Import-PSSession");
ImportSession.AddParameter("Session", SessionHolder);
powershell.Commands = ImportSession;
powershell.Invoke();
PSCommand GrabGroup = new PSCommand();
GrabGroup.AddCommand("Get-UnifiedGroupLinks");
GrabGroup.AddParameter("Identity", GroupAddress);
GrabGroup.AddParameter("LinkType", "Members");
powershell.Commands = GrabGroup;
Collection<PSObject> PSOutput_GroupMembers = powershell.Invoke();
foreach (PSObject outputItem in PSOutput_GroupMembers)
{
//Process Members
}
}
The key seems to be that I need to Import the session before I can begin using it.

Some of the PowerShell module (Cluster cmdlets) does not get loaded when I create RunSpace on a localhost without providing runspaceconnectioninfo

Please refer the sample below:
RunspaceSample(string.Empty); fails with The term 'Add-VMToCluster' is not recognized as the name of a cmdlet.
Whereas the RunspaceSample("localhost") or RunspaceSample("somecomputerName") succeed. Any pointer why is it ? Does including RunspaceConnectionInfo changes the powershell version used or RunspaceConfiguration used for execution ?
Also what would be the performance impact if I create Runspace with RunSpaceConnectionInfo with ComputerName = "localhost" even for executing powershell script on a local computer ?.
Thanks
public static void RunspaceSample(string computerName)
{
Runspace rs;
if (string.IsNullOrEmpty(computerName))
{
rs = RunspaceFactory.CreateRunspace();
}
else
{
var connectionInfo = new WSManConnectionInfo
{
OperationTimeout = 10000,
OpenTimeout = 10000,
ComputerName = computerName
};
rs = RunspaceFactory.CreateRunspace(connectionInfo);
}
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
string script = #"$ComputerName = 'somevm'; $null = Add-VMToCluster -Name $ComputerName -VMName $ComputerName -ErrorAction SilentlyContinue -verbose";
ps.AddScript(script);
Console.WriteLine("Script: {0}", script);
Console.WriteLine("------------------------");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
if (ps.HadErrors)
{
var sb = new StringBuilder();
foreach (var errorRecord in ps.Streams.Error)
{
sb.AppendFormat("\nError: {0} CategoryInfo: {1}", errorRecord.Exception.Message, (errorRecord.CategoryInfo != null) ? errorRecord.CategoryInfo.ToString() : string.Empty);
}
var errorMessage = sb.ToString();
Console.WriteLine(errorMessage);
}
}
The FailoverClusters module is only available in 64-bit PowerShell sessions. Making this assembly as 64 bit assembly resolved the module not found issue.

Create exchange mailbox in c#

I want to create Mailbox in exchange server 2013 using c# .
I tried lots of codes but each one gets an error that there is no obvious solution to solve it.
my code is
public static Boolean CreateUser(string FirstName, string LastName, string Alias,string PassWord, string DomainName, string OrganizationalUnit)
{
string Name = FirstName + " " + LastName;
string PrincipalName = FirstName + "." + LastName + "#" + DomainName;
Boolean success = false;
string consolePath = #"C:\Program Files\Microsoft\Exchange Server\V15\bin\exshell.psc1";
PSConsoleLoadException pSConsoleLoadException = null;
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(consolePath, out pSConsoleLoadException);
SecureString spassword = new SecureString();
spassword.Clear();
foreach (char c in PassWord)
{
spassword.AppendChar(c);
}
PSSnapInException snapInException = null;
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open();
Pipeline pipeLine = myRunSpace.CreatePipeline();
Command myCommand = new Command("New-MailBox");
myCommand.Parameters.Add("Name", Name);
myCommand.Parameters.Add("Alias", Alias);
myCommand.Parameters.Add("UserPrincipalName", PrincipalName);
myCommand.Parameters.Add("Confirm", true);
myCommand.Parameters.Add("SamAccountName", Alias);
myCommand.Parameters.Add("FirstName", FirstName);
myCommand.Parameters.Add("LastName", LastName);
myCommand.Parameters.Add("Password", spassword);
myCommand.Parameters.Add("ResetPasswordOnNextLogon", false);
myCommand.Parameters.Add("OrganizationalUnit", OrganizationalUnit);
pipeLine.Commands.Add(myCommand);
pipeLine.Invoke(); // got an error here
myRunSpace.Dispose();
}
and call it :
Boolean Success = CreateUser("firstname", "lastName", "aliasName", "AAaa12345", "mydomain.com", "mydomain.com/Users");
which I get this error :
Additional information: The term 'New-MailBox' 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.
and another code that I test is:
string userName = "administrator";
string password = "mypass";
System.Security.SecureString securePassword = new System.Security.SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://{my server IP}/POWERSHELL/Microsoft.Exchange"),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
connectionInfo.MaximumConnectionRedirectionCount = 2;
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
//Create the command and add a parameter
powershell.AddCommand("Get-Mailbox");
powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
//Invoke the command and store the results in a PSObject collection
Collection<PSObject> results = powershell.Invoke();
//Iterate through the results and write the DisplayName and PrimarySMTP
//address for each mailbox
foreach (PSObject result in results)
{
Console.WriteLine(
string.Format("Name: { 0}, PrimarySmtpAddress: { 1}",
result.Properties["DisplayName"].Value.ToString(),
result.Properties["PrimarySmtpAddress"].Value.ToString()
));
}
}
}
and I get this error
Additional information: Connecting to remote server {Server IP Address} failed with the following error message : [ClientAccessServer=WIN-FRP2TC5SKRG,BackEndServer=,RequestId=460bc5fe-f809-4454-8472-ada97eacb9fb,TimeStamp=4/6/2016 6:23:28 AM] Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
I think I gave every permission which is needed to my administrator user and firewall is off but it doesn't work yet.
Any help or hint !!
thanks
Try this:
//Secure String
string pwd = "Password";
char[] cpwd = pwd.ToCharArray();
SecureString ss = new SecureString();
foreach (char c in cpwd)
ss.AppendChar(c);
//URI
Uri connectTo = new Uri("http://exchserver.domain.local/PowerShell");
string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
//PS Credentials
PSCredential credential = new PSCredential("Domain\\administrator", ss);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo, schemaURI, credential);
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
remoteRunspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = remoteRunspace;
ps.Commands.AddCommand("Get-Mailbox");
ps.Commands.AddParameter("Identity","user#domain.local");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine("{0,-25}{1}", result.Members["DisplayName"].Value,
result.Members["PrimarySMTPAddress"].Value);
}
I unchecked "prefer 32-bit" and changed platform target to x64, the problem was solved.
with the following code :
public class ExchangeShellExecuter
{
public Collection<PSObject> ExecuteCommand(Command command)
{
RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
PSSnapInException PSException = null;
PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(command);
Collection<PSObject> result = pipeline.Invoke();
return result ;
}
}
public class ExchangeShellCommand
{
public Command NewMailBox(string userLogonName,string firstName,string lastName,string password
,string displayName,string organizationUnit = "mydomain.com/Users",
string database = "Mailbox Database 1338667540", bool resetPasswordOnNextLogon = false)
{
try
{
SecureString securePwd = ExchangeShellHelper.StringToSecureString(password);
Command command = new Command("New-Mailbox");
var name = firstName + " " + lastName;
command.Parameters.Add("FirstName", firstName);
command.Parameters.Add("LastName", lastName);
command.Parameters.Add("Name", name);
command.Parameters.Add("Alias", userLogonName);
command.Parameters.Add("database", database);
command.Parameters.Add("Password", securePwd);
command.Parameters.Add("DisplayName", displayName);
command.Parameters.Add("UserPrincipalName", userLogonName+ "#mydomain.com");
command.Parameters.Add("OrganizationalUnit", organizationUnit);
//command.Parameters.Add("ResetPasswordOnNextLogon", resetPasswordOnNextLogon);
return command;
}
catch (Exception)
{
throw;
}
}
public Command AddEmail(string email, string newEmail)
{
try
{
Command command = new Command("Set-mailbox");
command.Parameters.Add("Identity", email);
command.Parameters.Add("EmailAddresses", newEmail);
command.Parameters.Add("EmailAddressPolicyEnabled", false);
return command;
}
catch (Exception)
{
throw;
}
//
}
public Command SetDefaultEmail(string userEmail, string emailToSetAsDefault)
{
try
{
Command command = new Command("Set-mailbox");
command.Parameters.Add("Identity", userEmail);
command.Parameters.Add("PrimarySmtpAddress", emailToSetAsDefault);
return command;
}
catch (Exception)
{
throw;
}
//PrimarySmtpAddress
}
}
and run with :
var addEmailCommand = new ExchangeShellCommand().AddEmail("unos4#mydomain.com","unos.bm65#yahoo.com");
var res2 = new ExchangeShellExecuter().ExecuteCommand(addEmailCommand);
var emailDefaultCommand = new ExchangeShellCommand().AddSetDefaultEmail("unos4#mydomain.com", "unos.bm65#yahoo.com");
var res3 = new ExchangeShellExecuter().ExecuteCommand(emailDefaultCommand);

Error message when running a c# powershell code

When I run the code below I get the following error at Response.Write( result.Properties["name"].Value);. "use the 'new' keyword to create and object instance."
I can't figure out how to fix this problem.
String sEmailAddress;
String sPassword;
sEmailAddress = Request.QueryString["value1"];
sPassword = Request.QueryString["value2"];
lbl1.Text = sEmailAddress + " " + sPassword;
SecureString sSecurePW = new SecureString();
foreach (char c in sPassword.ToCharArray())
sSecurePW.AppendChar(c);
PSCredential Credential = new PSCredential(sEmailAddress, sSecurePW);
PowerShell powershell = PowerShell.Create();
powershell.Runspace.SessionStateProxy.SetVariable("cred", Credential);
powershell.AddScript("$s = New-PSSession -ComputerName ExchDC01 -Credential $cred -Authentication Kerberos");
powershell.AddScript("invoke-command -session $s -scriptblock {Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase 'OU=TENANTS,DC=lab,DC=local' -SearchScope OneLevel | ft Name}");
// Collection<PSObject> results = powershell.Invoke();
foreach (PSObject result in powershell.Invoke())
{
Response.Write(result.Properties["name"].Value); //<-- Error:use the 'new' keyword to create and object instance.
}
}
Thanks in advance

Error while running AD commandlets in powershell from C#

I have tried executing AD commandlets in powershell using C# from the same machine. This works fine.
static void Main(string[] args)
{
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "activedirectory" });
Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);
myRunSpace.Open();
Pipeline pipeLine = myRunSpace.CreatePipeline();
Command myCommand = new Command("Get-ADUser");
myCommand.Parameters.Add("Filter", "sAMAccountName -eq 'user1'");
//myCommand.Parameters.Add("IncludeDeletedObjects");
pipeLine.Commands.Add(myCommand);
//Command restoreCommand = new Command("Restore-ADObject");
//pipeLine.Commands.Add(restoreCommand);
Console.WriteLine("Before Invoke");
Collection<PSObject> commandResults = pipeLine.Invoke();
Console.WriteLine("After Invoke");
foreach (PSObject cmdlet in commandResults)
{
//Console.WriteLine("Inside foreach");
string cmdletName = cmdlet.BaseObject.ToString();
System.Diagnostics.Debug.Print(cmdletName);
Console.WriteLine(cmdletName);
}
Console.ReadLine();
}
But while trying to run the same command remotely using the invoke command it gives the error The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program.
The following is my program :
static void Main(string[] args)
{
string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
string userName = "Domain\\Administrator";
string password = "Password";
SecureString securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machinename", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
PSCommand new1 = new PSCommand();
new1.AddCommand("Get-ADUser");
new1.AddParameter("identity", "CN=user1,DC=example,DC=com");
powershell.Commands = new1;
Collection<PSObject> results = powershell.Invoke();
foreach (PSObject obj in results)
{
PSMemberInfoCollection<PSPropertyInfo> propInfos = obj.Properties;
Console.WriteLine("********************");
foreach (PSPropertyInfo propInfo in propInfos)
{
string propInfoValue = (propInfo.Value == null) ? "" : propInfo.Value.ToString();
Console.WriteLine("{0} --> {1}", propInfo.Name, propInfoValue);
}
}
}
}
}
How can I achieve calling AD commandlets remotely?
Is there a way to invoke commands remotely using InitialSessionState rather than WSManConnectionInfo .
If I use invoke-command -computername $DC -ScriptBlock {Remove-ADUser -identity "user1"} -credential $cred - i get the error The term 'Remove-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program.
But it is possible to use command Remove-ADUser -identity "user1" -server $DC -credential $cred .How to directly execute the AD command in powershell from C# client?
You need to import the ActiveDirectory module in the remote runspace before executing the AD command e.g.:
powershell.Commands.AddCommand("Import-Module").AddArgument("ActiveDirectory");
powershell.Invoke();
powershell.Commands.Clear();

Categories

Resources