C# · 12月 25, 2021

如何通过C#将参数传递给PowerShell

我有问题通过C#传递参数到Power Shell

我收到以下异常:

“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]

我在这里失踪了什么?我怎么能做这个工作?

解决方法 例外与参数无关.要么不使用需要实现主机UI的命令(包括写入主机),要么实现自己的自定义主机(PSHost)和此UI(PSHostUserInterface).下面是一个简单主机的示例(如果您选择这种方式,MSDN上还有更多内容):
http://msdn.microsoft.com/en-us/library/windows/desktop/ee706559(v=vs.85).aspx

对于简单的任务,实现具有UI的主机可能太多了.您可以考虑简单地定义具有相同参数的函数Write-Host并实现它以使其在您的特定情况下工作(例如,[Console] :: WriteLine(…)).该功能应该在脚本中定义,或者更好地以不同的方式提供给它,例如,使用在全局范围中定义的脚本调用另一个脚本.

附:如果您有自定义主机,则使用CreateRunspace()重载之一,该重载将主机实例作为参数,以便链接主机和运行空间.