基本上我正在制作命令提示符GUI.用户在富文本框中看到命令提示符输出,并在下面的纯文本框中输入命令.我已成功完成这项工作,除了对我来说,似乎无法获得颜色信息.例如,如果我运行一个输出红色错误文本的程序,我没有得到颜色代码字节,它们根本就不在流中!
这就是我现在正在做的事情.要开始这个过程:
ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe");
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
this.promptProcess = Process.Start(startInfo);
Run Code Online (Sandbox Code Playgroud)
然后我创建一个从输出流中读取并将其发送到我的文本框的线程:
while (true)
{
while (this.stream.EndOfStream) ;
//read until there's nothing left in the stream, writing to the (locked) output box
byte [] buffer = new byte[1000];
int numberRead;
StringBuilder builder = new StringBuilder();
do
{
numberRead = this.stream.BaseStream.Read(buffer, 0, buffer.Length);
char[] characters = UTF8Decoder.GetChars(buffer, 0, numberRead);
builder.Append(characters);
}
while (numberRead == buffer.Length);
this.writeToOutput(builder.ToString());
} …
Run Code Online (Sandbox Code Playgroud) 我开始了一个新的 .NET Framework 4.7.2 库项目。我需要自动化 PowerShell 脚本,但 Visual Studio 参考中添加 UI 的“框架”选项卡没有将 System.Management.Automation 作为选项列出。所以我添加了对这个 Nuget 包的引用:
https://www.nuget.org/packages/System.Management.Automation/7.0.0
然后用这个代码:
PowerShell ps = PowerShell.Create();
ps.AddScript(@"C:\ps\function.ps1");
ps.AddArgument(1);
ps.AddArgument(2);
Collection<PSObject> results = ps.Invoke<PSObject>();
Run Code Online (Sandbox Code Playgroud)
我收到有关我没有直接引用的 DLL 版本的错误消息:
具有标识 'System.Management.Automation, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 的程序集 'System.Management.Automation' 使用 'System.Linq.Expressions, Version=4.2.2.0, Culture=neutral, PublicKeyToken =b03f5f7f11d50a3a' 其版本高于引用的程序集 'System.Linq.Expressions',标识为 'System.Linq.Expressions, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
我不确定如何解决这个问题,我想也许我以错误的方式添加了我的 PowerShell 自动化库引用。目前这样做的正确方法是什么?
在你指出一个旧答案之前,我发现了一个类似的问题,它指向一个不同的 Nuget 包,现在标记为“已弃用”,无论如何看起来都不是官方的。这让我很紧张。
https://www.nuget.org/packages/System.Management.Automation.dll/
我想使用 Invoke-Command 在本地计算机上的文件中运行脚本,以便我可以使用 -ArgumentList 传入参数。我遇到了一个我不明白的错误,所以我简化了我的命令。当我这样做时:
Invoke-Command -FilePath 'getprocess.ps1'
Run Code Online (Sandbox Code Playgroud)
getprocess.ps1的内容是:
Get-Process
Run Code Online (Sandbox Code Playgroud)
我收到的错误消息是:
Invoke-Command :无法使用指定的命名参数解析参数集。
行:1 字符:1
+ 调用命令 -FilePath 'getprocess.ps1'
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+FullyQualifiedErrorId:AmbigouslyParameterSet、Microsoft.PowerShell.Commands.InvokeCommandCommand
我对这个错误消息感到困惑。这是什么意思?我该如何让它发挥作用?