I'm writing a Cmdlet in C#.
At some points I want to have a colored output like PowerShell command:
Write-Host "Message" -ForegroundColor Green
My C# code is like this:
public class MyCmdlet : PSCmdlet
{
protected override void ProcessRecord()
{
// Something like: WriteHost("Message", Color.Green);
// ...
}
}
but the only options are Write-Warning, Write-Error, Write-Object, ...
So my question is:
Question: How can I put some lot on the output with colors?
You can use the Host property of PSCmdlet class to interact with host:
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
Also you could use Write-Host cmdlet from your code:
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
If you are targeting PowerShell v5, then you can use the WriteInformation method:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With