Powershell addscript and invoke from C# not displaying result on command line - c#

I've the below powershell script file
C:\user\deskptop\script1.ps1
The contents of the script is just the below:
get-process
i'm trying to create a C# console app to get the output of this script on console. When i execute the script outside C# it runs fine but when i execute it inside C# it doesn't produce anything. i'm trying use addscript and invoke.
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace InvokePowerShellScriptFrmCsharp1
{
class Program
{
static void Main(string[] args)
{
string script = #"C:\\Users\\Desktop\\script1.ps1";
PowerShell shell = PowerShell.Create();
shell.AddScript(script);
//shell.AddCommand("get-process");
shell.Invoke();
//shell.AddScript(script).Invoke();
Collection<PSObject> pSObjects = shell.Invoke();
foreach (PSObject p in pSObjects)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
}
When i execute the above i get the console with 'Press any key to continue' but no output before that.
but if i just try the below i get the result
shell.addcommand("get-process");
I want to get this working with addscript coz in the future if there is more than one command in the powershell script then i need to be able to execute the script from C# for desired results.
i've tried many links to try research but don't seem to be getting it to work.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
https://www.reddit.com/r/csharp/comments/692mb1/running_powershell_scripts_in_c/
Could someone please let me know where i could be going wrong.

Try loading the script contents first, then passing that to the AddScript method:
string script = File.ReadAllText(#"C:\Scripts\script1.ps1");

Related

Using to get PS script name from a C# DLL? Getting "Object reference not set to an instance of an object."

ERROR:
Object reference not set to an instance of an object.
I'm trying to create a DLL that can get the Entrypoint application name that is written in Powershell.
The layout is very simple:
In Powershell I add the line
Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')
then I create the object
$value = New-Object PS_get_value.Stack
and call the C# method
$rtn = $value.Get_stack()
If the Get_stack() method returns a basic string like "Test" it works fine….
BUT if I try to use the .net Assembly.GetEntryAssembly().Location (which should return the full path to the calling (parent) app), I get the error above.
I am trying to get the full path (or at least the filename) of the application script that is running in Powershell. I plan on using that value to validate that the program (PS script) is the one that should be running. If there is a different way for the C# code to get it that's fine. BTW if I run a normal program it works. I do know that there is something about managed code base, I'm not sure what that is.
Thanks for any help or direction your can give.
Code Example:
PS:
Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')
$addNum = New-Object PS_get_value.Stack
$_rtnKey = $addNum.Get_stack()
Write-Host "RTNed Key Version 2: $_rtnKey"
C# (the DLL):
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
namespace PS_get_value
{
public class Stack{
public string Get_stack()
{
string _test_a = g_stack();
return _test_a;
}
public string g_stack()
{
return System.Reflection.Assembly.GetEntryAssembly().Location;
}
}
}
Give it a try by returning one of the following:
Assembly.GetExecutingAssembly().Location
or
Assembly.GetExecutingAssembly().CodeBase

Get input from the user using ReadLine in c# code that runs as part of PowerShell script in PowerShell ISE

I need to prompting users for input in C# part of the code, but it doesn't work for me (gets empty input automagically) when run from PowerShell ISE. Code works as expected when run from just regular PowerShell command prompt (asks for the name)
$id = get-random
$code = #"
using System;
using System.Linq;
namespace Application
{
public class Program$id
{
public static void Main()
{
Console.WriteLine("Please enter your sweet name....");
String name = Console.ReadLine();
Console.WriteLine("Hello *"+name+" %" );
}
}
}
"#
Add-type -TypeDefinition $code -Language CSharp
iex "[Application.Program$id]::Main()"
When run in ISE the output is following (notice there is no chance to provide input):
PS C:\Users\Pavithra Kathirvel\Desktop> C:\Users\Pavithra Kathirvel\Desktop\demo.ps1
Please enter your sweet name....
Hello * %
As a beginner start with the basics in C# and powershell. If you are able to use one, it will be easier for you to learn the other. Also there are parts, which are in powershell faster than in c# and less code.
If you still want to execute your C# code in powershell, have a look at this link, it will run the script from a .cs file
Run a C# .cs file from a PowerShell Script
Also here is a really good tutorial for using c# in powershell:
https://blog.adamfurmanek.pl/2016/03/19/executing-c-code-using-powershell-script/

Invoking PS script from C# code (Visual studio 2017)

I am trying to invoke my PS script from C# code.
**PS code. -- Try.ps1**
Write-Host "HelloHost"
Write-Debug "HelloDebug"
Write-Output "HelloOutput"
echo "tofile" > $PSScriptRoot/a.txt
**C# code**
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
namespace TryitOut
{
class Program
{
static void Main(string[] args)
{
using (PowerShell pshell = PowerShell.Create())
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
pshell.AddScript(path + "\\Try.ps1");
IAsyncResult result = pshell.BeginInvoke();
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for PS script to finish...");
Thread.Sleep(1000);
}
Console.WriteLine("Finished!");
Console.ReadKey();
}
}
}
}
When I run "Try.ps1" independently it runs ok and creates a.txt ans shows console output as expected.
But, it not getting invoked/executed via this C# code.
Question 1. can you please help, what I am doing wrong?
Q 2. How can I see PS console output when invoking Try.ps1 via C# code
Thank you for your time :).
Dealing with output from the PowerShell object is done in two ways. One is the direct return values of the Invoke call, and the other is via various streams. In both cases, you are responsible for dealing with the data; the console does not automatically output them as when you run a script in the standard PowerShell window. For example, to get the results from Write-Object, you can add the following to your C# code after your while loop:
foreach(PSObject pso in pshell.EndInvoke(result))
{
Console.WriteLine(pso);
}
This works fine for the simple strings in your example, but for complex objects with multiple properties, you need to pull the individual properties by name. For example:
string propValue = pso.Members["PropertyName"].Value.ToString();
Have a look at a previous answer of mine to see one way to convert complex objects to your own type: Dealing with CimObjects with PowerShell Inside C#
Handle the debug, information, verbose, etc like this:
foreach(DebugRecord dbr in pshell.Streams.Debug)
{
Console.WriteLine(dbr);
}
You will need to add this to the start of your script as well:
$DebugPreference = 'continue'

C# Console Application Does NOT read from the command line, as it should

I have spent a good while trying to get this simple code to read from the command line:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
{
for (int i = 0; i < args.Length; ++i)
System.Console.WriteLine(args[i]);
}
else System.Console.WriteLine("NO COMMAND INPUT DETECTED");
System.Console.ReadLine();
}
}
}
When typing the command:
ConsoleApplication3.application "pleasework"
I get the following message in the command line:
NO COMMAND INPUT DETECTED
indicating that the command line is not working properly. Any thoughts? I am very bad with Visual Studio (this is 2012) so I imagine there is some special property I need to change or something ridiculous.
Thanks!
Using this:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
Console.Read();
}
}
}
I was able to go to my command prompt and run:
C:\ProjectPath\ConsoleApplication1\bin\debug\ConsoleApplivation1.exe "Test" "Test2"
With a result of:
2
Edit: It looks like you are running a ClickOnce Console Application. This complicates what you want to do, but it isn't impossible. Here are several resources that discuss this particular issue:
Processing Command Line Arguments in an Offline ClickOnce Application
Harvesting ClickOnce Command Line Arguments
How to pass arguments to an offline ClickOnce application
Your code seems to be okay.
You're probably not passing the argument properly.
Take the following steps:
Right-Click on your Project => Properties => Debug => insert "Pleasework" into the command line arguments => save and debug your code step-by-step.
And you'll see:

Input to console application in C#

I created a dll file for my matlab program. I integrated it into C# console application now I have to call this console application from php. The user selects an image whose imagepath should be passed as input in the C# console application.
I checked the console application my defining an image path and it works fine how can I program it to accept input from php aplication so that I can call exec(exepath imgpath)in php. I have to pass the image path to the matlab dll file too. My Console application is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using shoesddl;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
namespace shoes_describe
{
class Program
{
static void Main(string[] args)
{
shoesddl.shoes_describe obj = new shoesddl.shoes_describe();
MWArray img= "C:/Users/adithi.a/Desktop/dressimages/T1k5aHXjNqXXc4MOI3_050416.jpg";
obj.shoes(img);
}
}
}
I need the imgpath i.e img in the above program from php. How can I achieve it?
use Command Line Parameters. Your method is accepting parameters in string[] args. You can pass the image path alongwith the exe name, from your PHP code.
> exepath imgpath
That imagepath would available at args[0]

Categories