Is there a way to specify a font color when using write-output

前端 未结 5 1594
抹茶落季
抹茶落季 2021-02-07 02:25

I have a powershell script that gives some status output via write-output. I am intentionally not using write-host because the output may be captured and writt

5条回答
  •  无人及你
    2021-02-07 02:58

    I know this post is ancient, but this could come handy to someone out there.

    I wanted to change colors and the accepted answer was not the best solution. In my eyes, the following code is better solution as it takes advantage of the native PowerShell functionality:

    EDIT:

    # Print User message using String Array $message
    function PrintMessageToUser {
        param(
            [Parameter( `
                Mandatory=$True, `
                Valuefrompipeline = $true)]
            [String]$message
        )
        begin {
            $window_private_data = (Get-Host).PrivateData;
            # saving the original colors
            $saved_background_color = $window_private_data.VerboseBackgroundColor
            $saved_foreground_color = $window_private_data.VerboseForegroundColor
            # setting the new colors
            $window_private_data.VerboseBackgroundColor = 'Black';
            $window_private_data.VerboseForegroundColor = 'Red';
        }
        process {
            foreach ($Message in $Message) {
                # Write-Host Considered Harmful - see http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/
                # first way how to correctly write it
                #Write-host $message;
                Write-Verbose -Message $message -Verbose;
                # second correct way how to write it
                #$VerbosePreference = "Continue"
                #Write-Verbose $Message;
            }
        }
        end {
          $window_private_data.VerboseBackgroundColor = $saved_background_color;
          $window_private_data.VerboseForegroundColor = $saved_foreground_color;
        }
    
    } # end PrintMessageToUser
    

提交回复
热议问题