Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7989893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T12:52:05+00:00 2026-06-04T12:52:05+00:00

I use PS 2.0, VS2010, C# for call Powershell scripts (ps1 files) using C#.

  • 0

I use PS 2.0, VS2010, C# for call Powershell scripts (ps1 files) using C#.

I have this Unit Test and works fine:

output = UsingPowerShell(@".\test1.ps1, "");
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));

Script contents:

=================== test1.ps1 ==========================
$someVariable = "StringToBeVerifiedInAUnitTest" 
$someVariable
=================== End test1.ps1 ==========================

But this Unit test fails. I get this error message:

“Cannot invoke this function because the current host does not implement it”

        output = UsingPowerShell(@".\test2.ps1", "");
        Assert.IsTrue(output.Contains("test2.ps1"));

Script contents

    =================== test2.ps1 ==========================
$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentPath =  $MyInvocation.MyCommand.Path
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")
$scriptDir = Split-Path -parent $MyInvocation.MyCommand.Path

#Write-Host $currentExecutingPath
Write-Host $currentScriptName
Write-Host `r`nRuta: $scriptDir
    =================== End test2.ps1 ==========================

UsingPowerShell method:

public static string UsingPowerShell(string scriptPS, string parametros)
        {
            if (string.IsNullOrWhiteSpace(parametros)) return UsingPowerShell(scriptPS, new List<string> { });
            return UsingPowerShell(scriptPS, parametros.Split(' '));
        }

        public static string UsingPowerShell(string scriptPS, IList<string> parametros)
        {
            var builder = new StringBuilder();
            string answer = null;

            RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
            InitialSessionState iss = InitialSessionState.CreateDefault();
            using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
            {
                runspace.Open();

                //runspace.ApartmentState = System.Threading.ApartmentState.STA;
                //runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;

                RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                // create a pipeline and feed it the script text 
                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    Command command = new Command(scriptPS,true,true);
                    foreach (var param in parametros)
                    {
                        command.Parameters.Add(null, param);
                    }
                    pipeline.Commands.Add(command);

                    //pipeline.Commands.AddScript(cmdArg);
                    //runspace.SessionStateProxy.SetVariable("MyResponse", response);

                    pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                    Collection<PSObject> psresults = pipeline.Invoke();

                    //PSObject newResponse = (PSObject)runspace.SessionStateProxy.GetVariable("MyResponse");

                    //if you want to get a value from a variable in you script like so:
                    //Object resultcollection = runspace.SessionStateProxy.GetVariable("results");

                    // convert the script result into a single string 
                    var sb = new StringBuilder();
                    foreach (PSObject obj in psresults)
                    {
                        sb.AppendLine(obj.ToString());
                    }


                    answer = sb.ToString();
                    Console.WriteLine(answer);
                    //Console.WriteLine(psresults.ToArray()[0].ToString());

                    // check for errors (non-terminating) 
                    if (pipeline.Error.Count > 0)
                    {
                        //iterate over Error PipeLine until end 
                        while (!pipeline.Error.EndOfPipeline)
                        {
                            //read one PSObject off the pipeline 
                            var value = pipeline.Error.Read() as PSObject;
                            if (value != null)
                            {
                                //get the ErrorRecord 
                                var r = value.BaseObject as ErrorRecord;
                                if (r != null)
                                {
                                    //build whatever kind of message your want 
                                    builder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                                    builder.AppendLine(r.InvocationInfo.PositionMessage);
                                    builder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                                    builder.AppendLine(string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                                }
                            }
                        }
                        //return builder.ToString();
                    }

                    pipeline.Dispose();
                }

                runspace.Close();
            }

            return answer;

        }

Any suggestions?

UPDATE:

How Windows PowerShell Works
http://msdn.microsoft.com/en-us/library/ms714658(VS.85).aspx

Windows PowerShell operates within a hosting application (the default is powershell.exe) that exposes a command line to the user, and uses a host interface to communicate with the commands invoked by the command line. The hosting application can be a console application, a Windows application, or a Web application. In most cases, the hosting application uses its Main function to interact with the Windows PowerShell runtime through the internal host interface; however, a hosting application can optionally support its own custom host by implementing the PSHost class along with one or more related user interface classes. Together, these classes allow direct communication between the application and Windows PowerShell commands.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T12:52:07+00:00Added an answer on June 4, 2026 at 12:52 pm

    Write-host is not supported by the powershell host you are using.

    An easy workaround is to replace:

    Write-Host $currentScriptName
    Write-Host `r`nRuta: $scriptDir
    

    by:

    $currentScriptName
    "`r`nRuta: $scriptDir"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Help! This code works fine on my local VS2010 with TypeMock, however fails on
Is there a way to use the SQL Model (dbml) builder in VS2010 using
I'm using VS2010,C# to develop a Silverlight online game, I use keyboard for getting
I'm using C# and VS2010. I have a dll that I reference in my
I have a WPF application running with VS2010 .Net3.5 using Nhibernate with FluentNHibernate +
first, a little background. I am using VS2010 and have a WCF service that
I am using C# to develop an enterprise level application. I use VS2010 Modeling
I'm attempting to use C# as a scripting language using CSharpCodeProvider (using VS2010 and
I'm using several 32 bit PNG files in my VS2010 project and loading them
I use VS2010, C# to develop Silverlight 4 app, I use following code in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.