user829174
user829174

Reputation: 6362

How to pass arguments to PowerShell via C#

I having issues with passing arguments to PowerShell via C#

I am getting the following exception:

"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows"

cs:

private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
    string scriptParameters = "param1 param2";

    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptFile);
    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    foreach (string scriptParameter in scriptParameters.Split(' '))
    {
        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
        commandParameters.Add(commandParm);
        scriptCommand.Parameters.Add(commandParm);
    }
    pipeline.Commands.Add(scriptCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

ps:

Function Foo ($arg1, $arg2)
{
    Write-Host $arg1
    Write-Host $arg2
}
Foo $args[0] $args[1]

What am i missing here? how can i make this work?

Upvotes: 6

Views: 4800

Answers (1)

Roman Kuzmin
Roman Kuzmin

Reputation: 42035

The exception is not about arguments. Either do not use commands that require host UI implemented (Write-Host included) or implement you own custom host (PSHost) and this UI (PSHostUserInterface). Here is the example of a simple host (and there is much more on MSDN about this, if you choose this way): http://msdn.microsoft.com/en-us/library/windows/desktop/ee706559(v=vs.85).aspx

For simple tasks implementing a host with UI is too much, perhaps. You may consider simply to define a function Write-Host with the same arguments and implement it so that it works in your specific case (e.g. does [Console]::WriteLine(...)). This function should be defined in the script or better made available for it in a different way, e.g. invoke another script with it defined in the global scope.

P.S. And if you have your custom host then use one of the CreateRunspace() overloads that takes a host instance as an argument in order to link the host and the runspace.

Upvotes: 11

Related Questions