Read data From powershell script

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

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");
        }
    }

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

e.g
Test.ps1:
Get-Content .\aa.txt | ForEach-Object{$_ -replace “\s+”,“,”}

in c# or wpf:

PowerShellInstance.AddScript(Test.ps1);

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

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.

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);
                }
            }

You’ll have to be a bit more specific than “Not working” in order for anyone to help troubleshoot. :slight_smile: