Running powershell script with C# code - c#

When I try to run the script with my C# code. I get the following error:
"You cannot call a method on a null-valued expression."
Would this be my C# code that is wrong
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
Pipeline pipeLine = runSpace.CreatePipeline();
pipeLine.Commands.AddScript(#"D:\NewSites\test-new\ConfigureIIS7.ps1");
try
{
pipeLine.Invoke();
}
catch (Exception ex)
{
throw ex;
}
pipeLine.Stop();
runSpace.Close();
Or should I look for the problem in my powershell script? The shell script works when executed normally.
Thanks in advance.

I'm not a specialist at all but it seems your error is a POWERSHELL error.
See This for example.
I think the problem is located into your PowerShell script

You could try:
System.Diagnostics.Process.Start(#"D:\NewSites\test-new\ConfigureIIS7.ps1");

Related

"Common Language Runtime detected an invalid program." exception thrown when trying to run PowerShell script from C#

I am attempting to execute a PowerShell script from a C# Windows forms application.
Code I am using is as follows,
private void testButton_Click(object sender, EventArgs e)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command("D:\\MyScript.ps1");
CommandParameter testParam = new CommandParameter("hello");
myCommand.Parameters.Add(insurerParam);
pipeline.Commands.Add(myCommand);
pipeline.Invoke();
}
Whenever I execute this code it is throwing exception Common Language Runtime detected an invalid program.
Any help on where I am going wrong would be hugely appreciated as I am currently completely lost as I was so sure this would work (obviously not!).
TIA

Run Powershell from C#

I need to start a powershell script from C# and get the PSSSecurityException on pipeline.Invoke()
AuthorizationManager check failed.
My code:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(scriptfile);
pipeline.Commands.Add(scriptCommand);
pipeline.Invoke();
}
Questions
I suspect that I need to set PSCredential. But I can not promt for it, so I have to handle this in code. Can this be done in a secure way? (This was not the case)
Check out this SuperUser post: https://superuser.com/questions/106360/how-to-enable-execution-of-powershell-scripts
You probably just need to allow unsigned scripts to run. In the PS console, type the following:
set-executionpolicy remotesigned
Another resource echoes this: http://tgnp.me/2011/09/powershell-authorizationmanager-check-failed-resolution/
Give that a try and let me know what happens.
To capture the output from the script, try this:
Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
<here you can ToString the psObject for the output and write it line by line to your log>
}
The problem was that the script was placed on a share. To run scripts on this share I needed to add the share to Trusted Sites.

Powershell command through C# code

I want to add through C# code Powershell command or script (what is correct?) variable declaration with default value stored in C# variable.
For example, in Powershell I typing following line
$user = 'Admin'
I want to add this line in C# code.
powershell.AddScript(String.Format("$user = \"{0}\"", userName));
or
powershell.AddCommand(String.Format("$user = \"{0}\"", userName));
I try with AddCommand() but it throws exception. I use PS 2.0.
According to this article How to run PowerShell scripts from C#, you will need something like this:
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(String.Format("$user = \"{0}\"", userName));
pipeline.Commands.AddScript("#your main script");
// execute the script
Collection<psobject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
Also see Run Powershell-Script from C# Application question here on Stackoverflow.

Cannot invoke this function because the current host does not implement it c#

i know this is on this board, but im new, and nothing has really halped me, so i am hoping someone can provide some insight. i get the following error:
Cannot invoke this function because the current host does not implement it
here is my code
public static void runPowershellScript(string scriptName)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(scriptName);
pipeline.Invoke();
}
the variable i pass through is my script name, it doesnt have a problem.
You're probably using some functions which are host-specific, meaning that any process which hosts the PowerShell engine (e.g. the powershell.exe, powershell_ise.exe, your c# app) has to provide implementations for them.
In general, these would include the *-host functions (write-host, out-host, read-host), the transcript functions (start-transcript, stop-transcript), and some others.

C# passing an array to a powershell script

I'm attempting to run a powershell script from C#. I have no problem passing strings to the script however when I try to pass an array to the powershell script an exception gets thrown.
Here is the C# code:
string [] test = {"1","2","3","4"};
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
RunspaceInvoke invoker = new RunspaceInvoke();
invoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
Command myCmd = new Command(#"C:\test.ps1");
CommandParameter param = new CommandParameter("responseCollection", test);
myCmd.Parameters.Add(param);
pipeline.Commands.Add(myCmd);
// Execute PowerShell script
Collection<PSObject> results = pipeline.Invoke();
Here is the powershell script:
param([string[]] $reponseCollection)
$a = $responseCollection[0]
Every time this code executes it throws:
Cannot index into a null array.
I know that the code to execute the powershell script is correct when passing strings to the powershell script, it has been thoroughly tested.
It works perfectly fine for me.
Only thing I notice is that, in your script params you have $reponseCollection - the s is missing in response. Unless you made a mistake in entering it here, that would be the reason.
It might have seemed to work with string because Powershell doesn't care ( normally) when you assign / use a non-existing variable. But when you index into a null / non-existing variable, it does throw the error.
I think that you need to pass the array to powershell as a string in powershell array format, i.e.,
string test = "('1','2','3','4')";

Categories