Author Posts

June 1, 2015 at 3:45 am

Hi Developer,

How to read text data from the powershell script file if possible?

PowerShellInstance.AddScript(??????); // Read Data from the script

Collection PSOutput = PowerShellInstance.Invoke();

Reference:
http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx

Any Idea?
Thanks

June 1, 2015 at 3:59 am

You just need to enumerate the contents of your PSOutput variable. There's an example of that on the page you linked:

    // loop through each output object item
    foreach (PSObject outputItem in PSOutput)
    {
        // if null object was dumped to the pipeline during the script then a null
        // object may be present here. check for null to prevent potential NRE.
        if (outputItem != null)
        {
            //TODO: do something with the output item 
            Console.WriteLine(outputItem.BaseObject.GetType().FullName);
            Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
        }
    }

June 1, 2015 at 4:13 am

Dear,
I mean i want to run from powershell script like .ps1 in c# or wpf.

e.g
[b]Test.ps1:[/b]
Get-Content .\aa.txt | ForEach-Object{$_ -replace "\s+",","}

[b]in c# or wpf:[/b]
.................................
PowerShellInstance.AddScript(Test.ps1);
................................

so how to read or call from powershell script (ps1) in c# or wpf?
Thanks

June 1, 2015 at 4:17 am

Ah, I see. Something like this should work:

PowerShellInstance.AddScript(@"& 'C:\Path\To\Test.ps1'");

Here, you're just adding the equivalent PowerShell command to launch your script that you would use at a shell prompt. The call operator (&) and the single-quotation marks are there just in case the path to your script happens to contain spaces.

June 1, 2015 at 4:32 am

I tried but not working

using (PowerShell PowerShellInstance = PowerShell.Create())
{
string test = "Get-Content .\\aa.txt | ForEach-Object{$_ -replace \"\\s+\",\",\"}";

//PowerShellInstance.AddScript(test);[b] //Working[/b]

PowerShellInstance.AddScript(@"& 'D:\.........\bin\Debug\test.ps1'"); [b]//Not working[/b]

Collection PSOutput = PowerShellInstance.Invoke();

foreach (PSObject outputItem in PSOutput)
{

if (PowerShellInstance.Streams.Error.Count > 0)
{
// error records were written to the error stream.
// do something with the items found.
}

if (outputItem != null)
{
Console.WriteLine(outputItem);
}
}

June 1, 2015 at 4:33 am

You'll have to be a bit more specific than "Not working" in order for anyone to help troubleshoot. 🙂