How to run powershell script using c# in SharePoint solution - c#

i am getting below error while i am trying to run power-shell script in my SharePoint solution
The type initializer for
'System.Management.Automation.SessionStateScope' threw an exception.
just a reference
private void RunPowershellScript(string scriptFile, List<string> parameters)
{
PowerShell OPowerShell = null;
Runspace OSPRunSpace = null;
try
{
RunspaceConfiguration OSPRSConfiguration = RunspaceConfiguration.Create();
PSSnapInException OExSnapIn = null;
//Add a snap in for SharePoint. This will include all the power shell commands for SharePoint
PSSnapInInfo OSnapInInfo = OSPRSConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out OExSnapIn);
OSPRunSpace = RunspaceFactory.CreateRunspace(OSPRSConfiguration);
OPowerShell = PowerShell.Create();
OPowerShell.Runspace = OSPRunSpace;
Command Cmd1 = new Command("backup-spsite");
Cmd1.Parameters.Add("identity", "Your Site Coll URL");
Cmd1.Parameters.Add("path", "Back up file path");
OPowerShell.Commands.AddCommand(Cmd1 );
OSPRunSpace.Open();
OPowerShell.Invoke();
OSPRunSpace.Close();
}
catch (Exception Ex)
{
//Handle exception
}
finally
{
if (OSPRunSpace != null)
{
OSPRunSpace.Dispose();
OSPRunSpace = null;
}
if (OPowerShell != null)
{
OPowerShell.Dispose();
OPowerShell = null;
}
}

Related

OpenRemoteBaseKey UnauthorizedAccessException: Attempted to perform an unauthorized operation

I want to access the RegistryKeys of a remote PC in my network, if there is no terminalNumber passed as a parameter.
public LoginEntity(string ipAdress, string username, string password, string terminalNumber = "")
{
this.IpAdress = ipAdress;
this.Username = username;
this.Password = password;
if (terminalNumber == "")
{
try
{
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
rKey = rKey.OpenSubKey(#"SOFTWARE\Test", RegistryKeyPermissionCheck.ReadWriteSubTree);
var key = rKey.GetValue("terminalNumber", "NOTFOUND");
if (key is string)
{
if ((string)key != "NOTFOUND")
this.TerminalNumber = (string)key;
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("UnauthorizedException: Calling TerminalNumber from Remote Registry Keys");
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("IOException: Remote PC not available");
}
}
else
this.TerminalNumber = terminalNumber;
}
Due to safety reasons the Subkey in this example is called 'Test'.
But at
RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
the application throws an UnauthorizedAccessException.
What I did:
I already run Visual Studio 2019 as an administator.
The LoginEntity was instantiated in a Task*. (As I am using WPF, I don't want my UI to freeze, so I run it in a Task).
*The Task call is located in the MainWindow()-Constructor of my WPF-Application
Task.Run(() =>
{
List<LoginEntity> loginUser = Utility.ReadLoginDataFromCsv(loginUserPath);
this.Dispatcher.Invoke(() =>
{
Listview.ItemsSource = loginUser;
lblUserLoading.Content = "";
});
});
public static List<LoginEntity> ReadLoginDataFromCsv(string path, bool ignoreFirstLine = false)
{
List<LoginEntity> list = new List<LoginEntity>();
var lines = File.ReadAllLines(path, Encoding.UTF8);
if (ignoreFirstLine)
lines = lines
.Skip(1)
.ToArray();
foreach (string line in lines)
{
var rowData = line.Split(';');
LoginEntity le = new LoginEntity(rowData[0], rowData[1], rowData[2], rowData[3]);
if (le.IpAdress != "" && le.Username != "" && le.Password != "")
list.Add(le);
}
return list;
}
Does anyone know why I get the UnAuthorizedException and how I can get rid of it?

How to pass variables from c# to ssis package

I am trying to build an application with ASP.NET that execute SSIS Package,so I want to pass variables from the application to this Package.
I want to know if there is some configuration missed in SSIS.
var a = demande_provision_creance.Année;
var t = demande_provision_creance.Trimestre;
var e = demande_provision_creance.Etat;
var i = demande_provision_creance.ID;
db.SaveChanges();
try
{
String pkgLocation = #"C:\PROVISION_CREANCES.dtsx";
Application app = new Application();
Package ssisPackage = null;
ssisPackage = app.LoadPackage(pkgLocation, null);
Microsoft.SqlServer.Dts.Runtime.Variables vars = ssisPackage.Variables;
vars["User::Annee"].Value = a;
vars["User::trimestre"].Value = t;
vars["User::etat"].Value = e;
vars["User::id_demande"].Value = i;
Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = ssisPackage.Execute(null, vars, null, null, null);
if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in ssisPackage.Errors)
{
x += string.Concat("Package Execution results: {0}", local_DtsError.Description.ToString());
}
}
}
catch (DtsException ex)
{
// Exception = ex.Message;
}
return Json(x, JsonRequestBehavior.AllowGet);
You are almost there, you don't need to provide the variables scope beside of the variables name:
vars["Annee"].Value = a;
vars["trimestre"].Value = t;
vars["etat"].Value = e;
vars["id_demande"].Value = i;
Providing the scope is used within a script component or script task, but not when working with packages programatically.
Working with Variables Programmatically

Uninstalling product with WinRM and C#

I'm using WSManAutomation to remotely manage servers.
I need to install and uninstall applications on remote servers that have WinRM over HTTPS enabled. The connection is not a problem
So far the code below executes msiexec.exe in the remote host as I can see it in the list of processes but it does not execute the uninstall command.
public void UninstallProduct(string path, string target, string username = null, string password = null)
{
IWSMan wsman = new WSManClass();
IWSManConnectionOptions options = (IWSManConnectionOptions)wsman.CreateConnectionOptions();
if (options != null)
{
try
{
options.UserName = username;
options.Password = password;
int iFlags = (int)_WSManSessionFlags.WSManFlagCredUsernamePassword;
IWSManSession session = (IWSManSession)wsman.CreateSession(string.Format("https://{0}:5986/wsman", target), iFlags, options);
// IWSManSession session = (IWSManSession)wsman.CreateSession(string.Format("http://{0}/wsman", target), 0, options);
if (session != null)
{
try
{
string strResource = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process";
string strInputParameters =string.Format("<p:Create_INPUT xmlns:p=\"{0}\"><p:CommandLine>\"{1}\"</p:CommandLine></p:Create_INPUT>", "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process",path);
var reply = session.Invoke("Create", strResource, strInputParameters);
Console.WriteLine(reply);
Console.WriteLine();
}
finally
{
Marshal.ReleaseComObject(session);
}
}
}
finally
{
Marshal.ReleaseComObject(options);
}
}
}
The call to the method above would be:
obj.UninstallProduct(#"C:\Windows\System32\msiexec.exe /x {E499AB77-9B27-416CB9B6F-4A171D02BB31} /passive", "hostname", #"hostname\Administrator", "password");
Do you know why the command does not get executed?
Should I use another way to uninstall a product?
Thanks in advance.
Finally I came across a way to do this using remote PowerShell
string command = string.Format("(Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -match {0}}).Uninstall()", productName);
PSCredential credential = new PSCredential(username, securePassword);
string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(true, target, 5986, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline(command);
try
{
Collection<PSObject> results = pipeline.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process");
}
finally
{
runspace.Close();
}
}

How I can update the extensionAttribute3 Attribute in Active Directory with Powershell class in c#?

hi i want update the active directory with powershell and asp.net for this i use this code:
costCenter = "777";
public string SetADUser(string Auth_Password,string sAMAccountName, string CostCenter)
{
Security key = new Security();
try
{
SecureString pw = new SecureString();
foreach (char x in Auth_Password)
{
pw.AppendChar(x);
}
InitialSessionState initial = InitialSessionState.CreateDefault();
Environment.SetEnvironmentVariable("ADPS_LoadDefaultDrive", "0");
initial.ImportPSModule(new string[] { "ActiveDirectory" });
PSCredential crend = new PSCredential(ADNAME, pw);
using (Runspace runspace = RunspaceFactory.CreateRunspace(initial))
{
runspace.Open();
using (Pipeline p = runspace.CreatePipeline())
{
Command command = new Command("Set-ADUser");
command.Parameters.Add("Identity", sAMAccountName);
command.Parameters.Add("Replace","#{extensionAttribute3=" + "'" + CostCenter + "'" + "}"); ?? what is here wrong
//command.Parameters.Add("extensionAttribute3", CostCenter);
command.Parameters.Add("Credential", crend);
p.Commands.Add(command);
p.Invoke();
return string.Empty;
}
}
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
}
}
this is the error:
The Parameter "Replace" can not bind. The Value "#{extensionAttribute3='777'}" from typ "System.String" can not convert to "System.Collections.Hashtable".
How I can do this?
#{} is a powershell-shortcut to create a hashtable. In C# you should create a hashtable in the normal C#-way.
var ht = new Hashtable { { "extensionAttribute3", CostCenter } };
command.Parameters.Add("Replace", ht);

How to pass variables to an SSIS package from a C# application

Basically i am trying to build an application that uses SSIS to run a series of sql stuff.
Here is my code thus far:
public JsonResult FireSSIS()
{
string x = string.Empty;
try
{
Application app = new Application();
Package package = null;
package = app.LoadPackage(#"C:\ft\Package.dtsx", null);
Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = package.Execute();
if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in package.Errors)
{
x += string.Concat("Package Execution results: {0}", local_DtsError.Description.ToString());
}
}
}
catch (DtsException ex)
{
// Exception = ex.Message;
}
return Json(x, JsonRequestBehavior.AllowGet);
}
Does anybody know how to pass a variable to the package itself in this way?
You need to use the Package.Variables property.
Package package = null;
package = app.LoadPackage(#"C:\ft\Package.dtsx", null);
package.Variables["User::varParam"].Value = "param value";
Try that:
Microsoft.SqlServer.Dts.RunTime.Variables myVars = package.Variables;
myVars["MyVariable1"].Value = "value1";
myVars["MyVariable2"].Value = "value2";
Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = package.Execute(null, myVars, null, null, null);

Categories

Resources