Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write-Host -ForegroundColor Green equivalent in PSCmdlet in C#

Tags:

c#

powershell

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?

like image 239
mehrandvd Avatar asked Dec 07 '25 01:12

mehrandvd


1 Answers

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
like image 66
user4003407 Avatar answered Dec 08 '25 15:12

user4003407