2

I am editing a script which I need to convert to exe. It has a few Write-Host outputs of the status of the script when running. This causing the exe of the script to show up dialog boxes to the user forcing them to click OK 3 or 4 times before the script finishes.

I'd like to keep the Write-Host output but just hide them (the dialog boxes) when the end user executes it from the exe.

Is this possible? I have looked into [void] which the code doesn't like. The only other way I can get to work is just commenting it out with #, but I'm sure there's a better way.

Example of what I want hidden/suppressed:

Write-Host "Current Status = " $status
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Drekko
  • 69
  • 2
  • 9

2 Answers2

5

Per the comments you should use Write-Verbose instead of Write-Host as this will give you the functionality you want with very little effort. However to use Write-Verbose there's a couple of other changes you'll need to make:

First you'll need to add this to the top of your script:

 [cmdletbinding()]
 Param()

This gives your script a set of default parameters one of which includes -Verbose which enables any Write-Verbose messages to be displayed when used.

Secondly (based on the example you gave) you might need to slightly rewrite some of your (now) Write-Verbose string statements. For example:

write-host "Current Status = " $status

Works with Write-Host because it takes an array of strings as input. The same is not true of Write-Verbose, it only takes a single string, so the above example would need to be changed to:

Write-Verbose "Current Status =  $status"

Note that by using double quote strings the variable will still be expanded.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
0

You can try this:

function Remove-WriteHost
{
   [CmdletBinding(DefaultParameterSetName = 'FromPipeline')]
   param(
     [Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')]
     [object] $InputObject,

     [Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)]
     [ScriptBlock] $ScriptBlock
   )

   begin
   {
     function Cleanup
     {
       # clear out our proxy version of write-host
       remove-item function:\write-host -ea 0
     }

     function ReplaceWriteHost([string] $Scope)
     {
         Invoke-Expression "function ${scope}:Write-Host { }"
     }

     Cleanup

     # if we are running at the end of a pipeline, need to immediately inject our version
     #    into global scope, so that everybody else in the pipeline uses it.
     #    This works great, but dangerous if we don't clean up properly.
     if($pscmdlet.ParameterSetName -eq 'FromPipeline')
     {
        ReplaceWriteHost -Scope 'global'
     }
   }
}
Remove-WriteHost

Now try:

  Write-Host "Something"

Output will be nothing.

Refer: THIS

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45