如何从调用该PowerShell脚本的C#代码答复读主机?

时间:2019-04-24 22:14:15

标签: c# powershell

我需要从C#代码内部运行PowerShell脚本。那很容易。但是,然后,我的PowerShell脚本包含了几个读取主机命令。通常,脚本执行将停止,并且用户应手动向PowerShell控制台输入一些值作为答案。但是我需要从执行和控制该脚本流的C#中相同的代码回答这些读取主机请求。换句话说,我需要我的脚本在某个时候停止并等待从C#代码中输入一些数据,然后获取并继续执行。

我发现了如何从C#运行PS,发现了如何在启动C#时将参数或初始变量从C#传递给PS脚本,但是我找不到任何方法可以使我的脚本等待主机中的某些数据应用程序,接收它并继续在宿主应用程序内执行,所有这些在脚本运行时而不是在启动时执行。

您能指导我寻找可能有用的搜索方向或代码吗?

2 个答案:

答案 0 :(得分:2)

您可以在流程的WriteLine()上致电StandardInput。这将为脚本中的一个Read-Host提供数据。

为此,请确保将各个UseShellExecute中的ProcessStartInfo设置为false,并将其RedirectStandardInput设置为true

例如

    Process p = Process.Start(new ProcessStartInfo()
    {
        FileName = "powershell",
        Arguments = @"C:\Users\Konstantin\ps.ps1",
        UseShellExecute = false,
        RedirectStandardInput = true,
    });

    p.StandardInput.WriteLine("abc");

将为脚本Read-Host的第一个C:\Users\Konstantin\ps.ps1提供“ abc”。

如果有更多Read-Host个电话,请再次致电WriteLine()。或者,您可以将字符串连接与StandardInput.NewLine一起使用,而只需使用Write。例如

p.StandardInput.Write("abc" + StandardInput.NewLine + "xyz" + StandardInput.NewLine);

将为第一个Read-Host提供“ abc”,为第二个import numpy as np lst = np.array([1,2,3,4,5,5,5,5,5,6,7,8]) cnt5 = (lst==5).cumsum() np.arange(len(lst))[cnt5==3][0] # 6 提供“ xyz”。

答案 1 :(得分:0)

如果您在进程内调用PowerShell脚本,则覆盖procedure TForm1.LogInClick(Sender: TObject); begin if (Username.Text <> '') And (Password.Text <> '') then begin loginQuery.SQL.Clear; //use parameter method loginQuery.SQL.Text := 'Select Password from MYGUESTS where FIRSTNAME = :theID'; loginQuery.ParamByName('theID').AsString := Username.Text; loginQuery.Open(); passwords := loginQuery.FieldByName('Password').AsString; if(passwords = Password.Text) then begin with form3 do begin Show; Username.Clear; Password.Clear; Form1.Hide; end; end else begin ShowMessage('Wrong username or password. please re-enter'); end; end else begin ShowMessage('Please enter something'); end; end; 行为的唯一方法是为该进程定义一个自定义Read-Host。该行为由方法PSHost定义。这是您仅需覆盖PSHostUserInterface.ReadLine的基本示例。

Read-Host

注意:显示的每个未抛出using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Runspaces; using System.Security; namespace CustomHostExample { public static class Program { public static void Main() { var host = new CustomPSHost(); using (Runspace rs = RunspaceFactory.CreateRunspace(host)) using (PowerShell pwsh = PowerShell.Create()) { rs.Open(); pwsh.Runspace = rs; pwsh.AddCommand("Read-Host").Invoke(); } } } public class CustomPSHost : PSHost { public override string Name => "Custom Host"; public override Version Version => new Version(1, 0, 0, 0); public override Guid InstanceId { get; } = Guid.NewGuid(); public override PSHostUserInterface UI { get; } = new CustomPSHostUserInterface(); public override CultureInfo CurrentCulture => CultureInfo.CurrentCulture; public override CultureInfo CurrentUICulture => CultureInfo.CurrentUICulture; public override void EnterNestedPrompt() => throw new NotImplementedException(); public override void ExitNestedPrompt() => throw new NotImplementedException(); public override void NotifyBeginApplication() => throw new NotImplementedException(); public override void NotifyEndApplication() => throw new NotImplementedException(); public override void SetShouldExit(int exitCode) => throw new NotImplementedException(); } public class CustomPSHostUserInterface : PSHostUserInterface { public override PSHostRawUserInterface RawUI { get; } = new CustomPSHostRawUserInterface(); public override string ReadLine() { return Console.ReadLine(); } public override Dictionary<string, PSObject> Prompt( string caption, string message, Collection<FieldDescription> descriptions) => throw new NotImplementedException(); public override int PromptForChoice( string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice) => throw new NotImplementedException(); public override PSCredential PromptForCredential( string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) => throw new NotImplementedException(); public override PSCredential PromptForCredential( string caption, string message, string userName, string targetName) => throw new NotImplementedException(); public override SecureString ReadLineAsSecureString() => throw new NotImplementedException(); public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) => throw new NotImplementedException(); public override void Write(string value) => throw new NotImplementedException(); public override void WriteDebugLine(string message) => throw new NotImplementedException(); public override void WriteErrorLine(string value) => throw new NotImplementedException(); public override void WriteLine(string value) => throw new NotImplementedException(); public override void WriteProgress(long sourceId, ProgressRecord record) => throw new NotImplementedException(); public override void WriteVerboseLine(string message) => throw new NotImplementedException(); public override void WriteWarningLine(string message) => throw new NotImplementedException(); } public class CustomPSHostRawUserInterface : PSHostRawUserInterface { public override ConsoleColor BackgroundColor { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override Size BufferSize { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override Coordinates CursorPosition { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override int CursorSize { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override ConsoleColor ForegroundColor { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override Coordinates WindowPosition { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override Size WindowSize { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override string WindowTitle { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override bool KeyAvailable => throw new NotImplementedException(); public override Size MaxPhysicalWindowSize => throw new NotImplementedException(); public override Size MaxWindowSize => throw new NotImplementedException(); public override void FlushInputBuffer() => throw new NotImplementedException(); public override BufferCell[,] GetBufferContents(Rectangle rectangle) => throw new NotImplementedException(); public override KeyInfo ReadKey(ReadKeyOptions options) => throw new NotImplementedException(); public override void ScrollBufferContents( Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill) => throw new NotImplementedException(); public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) => throw new NotImplementedException(); public override void SetBufferContents(Rectangle rectangle, BufferCell fill) => throw new NotImplementedException(); } } 的方法都将实现,否则PowerShell将死锁或抛出。根据调用NotImplementedException的其他内容,将需要实现更多方法。