简体   繁体   中英

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?

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 (eg does [Console]::WriteLine(...) ). This function should be defined in the script or better made available for it in a different way, eg invoke another script with it defined in the global scope.

PS 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM