C# 在C中的PSCmdlet中写入主机-ForegroundColor绿色等效项#
我正在用C#编写Cmdlet 在某些情况下,我希望有一个彩色输出,如PowerShell命令:C# 在C中的PSCmdlet中写入主机-ForegroundColor绿色等效项#,c#,powershell,C#,Powershell,我正在用C#编写Cmdlet 在某些情况下,我希望有一个彩色输出,如PowerShell命令: Write-Host "Message" -ForegroundColor Green 我的C代码是这样的: public class MyCmdlet : PSCmdlet { protected override void ProcessRecord() { // Something like: WriteHost("Message", Color.Green);
Write-Host "Message" -ForegroundColor Green
我的C代码是这样的:
public class MyCmdlet : PSCmdlet
{
protected override void ProcessRecord()
{
// Something like: WriteHost("Message", Color.Green);
// ...
}
}
但唯一的选项是写入警告
,写入错误
,写入对象
所以我的问题是:
问题:如何在输出中添加颜色?该类具有设置颜色的属性:
Console.ForegroundColor = ConsoleColor.Green;
Console.BackgroundColor = ConsoleColor.Red;
(不是很好的颜色组合:-)
现有值为当前颜色:保存以还原
重要提示:除了
Write Host
之外,其他cmdlet并不认为它们正在写入具有颜色的内容–它们可以重定向到文件。此外,Write Host
的ForegroundColor
和BackgroundColor
的可能值受正在使用的PSH主机的影响。例如,使用控制台属性,您可以修改每种颜色的显示方式,但在ISE中这是不可能的
您是否考虑过只调用Microsoft.PowerShell.Commands.WriteHostCommand
?您可以使用PSCmdlet
类的属性与主机进行交互:
Add-Type -TypeDefinition @‘
using System;
using System.Management.Automation;
[Cmdlet(VerbsDiagnostic.Test, "HostUIWrite")]
public class TestHostUIWriteCmdlet : PSCmdlet {
protected override void ProcessRecord() {
Host.UI.WriteLine(ConsoleColor.Green, Host.UI.RawUI.BackgroundColor, "SomeText");
}
}
’@ -PassThru|Select-Object -ExpandProperty Assembly|Import-Module
Test-HostUIWrite
您还可以从代码中使用Write-Host
cmdlet:
Add-Type -TypeDefinition @‘
using System;
using System.Management.Automation;
using Microsoft.PowerShell.Commands;
[Cmdlet(VerbsDiagnostic.Test, "WriteHost")]
public class TestWriteHostCmdlet : PSCmdlet {
protected override void ProcessRecord() {
using(PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) {
ps.
AddCommand(new CmdletInfo("Write-Host", typeof(WriteHostCommand))).
AddParameter("Object", "SomeText").
AddParameter("ForegroundColor", ConsoleColor.Yellow).
Invoke();
}
}
}
’@ -ReferencedAssemblies Microsoft.PowerShell.Commands.Utility -PassThru|Select-Object -ExpandProperty Assembly|Import-Module
Test-WriteHost
如果您的目标是PowerShell v5,则可以使用WriteInformation
方法:
Add-Type -TypeDefinition @‘
using System;
using System.Management.Automation;
[Cmdlet(VerbsDiagnostic.Test, "WriteInformation")]
public class TestWriteInformationCmdlet : PSCmdlet {
protected override void ProcessRecord() {
WriteInformation(new HostInformationMessage { Message="SomeText",
ForegroundColor=ConsoleColor.Red,
BackgroundColor=Host.UI.RawUI.BackgroundColor,
NoNewLine=false
}, new[] { "PSHOST" });
}
}
’@ -PassThru|Select-Object -ExpandProperty Assembly|Import-Module
Test-WriteInformation
System.Console
与PSH的关系如何?此外,我想分别为每个Write-*
使用颜色。使用您的解决方案,我应该为每个写入设置控制台.ForegroundColor
。您是否建议使用Microsoft.PowerShell.Commands.WriteHostCommand的教程或文档?@mehrandvd不提供教程建议(它们老化太快)。但从另一个CmdLet中找到使用一个CmdLet的示例应该不难。是的,要混合控制台输出中的颜色,您需要在每次颜色需要更改时设置这些属性(我通常编写帮助程序来设置颜色、写入、恢复颜色)。@mehrandvd FIrst hit on a search告诉我