gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:09:43 24 4
gpt4 key购买 nike

我在通过 C# 向 PowerShell 传递参数时遇到问题

我收到以下异常:

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

附言:

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

我在这里错过了什么?我怎样才能使它工作?

最佳答案

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

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

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

关于c# - 如何通过 C# 将参数传递给 PowerShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12930762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com