237

I want my PowerShell script to print something like this:

Enabling feature XYZ......Done

The script looks something like this:

Write-Output "Enabling feature XYZ......."
Enable-SPFeature...
Write-Output "Done"

But Write-Output always prints a new-line at the end so my output isn't on one line. Is there a way to do this?

1

21 Answers 21

228

Write-Host -NoNewline "Enabling feature XYZ......."

Sign up to request clarification or add additional context in comments.

8 Comments

Downvoted because the OP's example specifically uses Write-Output, which has vastly different function than Write-Host. Readers should note this big discrepency before copy/pasting the answer.
I agree with @NathanAldenSr, Write-Host does not help if you are trying to output to a file etc.
Write-Host is almost never the right answer. It's the equivalent of doing >/dev/tty in Unixland.
Write-Progress may be appropriate in some cases, see example below.
Write-Host is the same as Write-Information and is redirectable as output stream 6. So you'd redirect it to a file as 6>output.txt. It doesn't have a "mind of its own," it's just not knowledge you can bring over from Unixland, is all, so lots of people misunderstand it.
|
72

Unfortunately, as noted in several answers and comments, Write-Host can be dangerous and cannot be piped to other processes and Write-Output does not have the -NoNewline flag.

But those methods are the "*nix" ways to display progression, the "PowerShell" way to do that seems to be Write-Progress: it displays a bar at the top of the PowerShell window with progress information, available from PowerShell 3.0 onward, see manual for details.

# Total time to sleep
$start_sleep = 120

# Time to sleep between each notification
$sleep_iteration = 30

Write-Output ( "Sleeping {0} seconds ... " -f ($start_sleep) )
for ($i=1 ; $i -le ([int]$start_sleep/$sleep_iteration) ; $i++) {
    Start-Sleep -Seconds $sleep_iteration
    Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) ( " {0}s ..." -f ($i*$sleep_iteration) )
}
Write-Progress -CurrentOperation ("Sleep {0}s" -f ($start_sleep)) -Completed "Done waiting for X to finish"

And to take the OP's example:

# For the file log
Write-Output "Enabling feature XYZ"

# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... " )

Enable-SPFeature...

# For the operator
Write-Progress -CurrentOperation "EnablingFeatureXYZ" ( "Enabling feature XYZ ... Done" )

# For the log file
Write-Output "Feature XYZ enabled"

4 Comments

I think this is best solution for showing the status. If you need to have a log or something you have to life with the linebreak of Write-Output.
Agreed, plus the point of progressive display is just "to be fancy" for live installing, there's no point in having it in log files: print "start doing something" then "done doing something"
Downvoted because while the example may be displaying a status, the question is how to output text, not how to use a progress bar.
Maybe I bothered to read and answer the question in the description... but you seem to know best :-)
12

While it may not work in your case (since you're providing informative output to the user), create a string that you can use to append output. When it's time to output it, just output the string.

Ignoring of course that this example is silly in your case but useful in concept:

$output = "Enabling feature XYZ......."
Enable-SPFeature...
$output += "Done"
Write-Output $output

Displays:

Enabling feature XYZ.......Done

7 Comments

This may work in the specific example provided, but there is still an extra line feed produced by Write-Output. Reasonable workaround, but not a solution.
This is not the point since entire output appears after the feature is installed.
I don't understand, who gives more than 1 upwote to this question, because This is not the point since entire output appears AFTER the feature is installed
"Ignoring of course that this example is silly in your case but useful in concept:"
@shufler It's not useful in concept at all. It's functionally no different from assigning the whole value to $output right off the bat.
|
9

Yes, as other answers have states, it cannot be done with Write-Output. Where PowerShell fails, turn to .NET, there are even a couple of .NET answers here but they are more complex than they need to be.

Just use:

[Console]::Write("Enabling feature XYZ.......")
Enable-SPFeature...
Write-Output "Done"

It is not purest PowerShell, but it works.

3 Comments

Downvoted because this behaves just like Write-Host, except people will not expect it.
[Console]::Write is even worse than Write-Host, which you can at least intercept if you know that it's fd 6. This bypasses all standard open fds and just hits the console directly.
Upvoted 'cause this is the one that works for my case, where I move the cursor $string.Length times to the left with ANSI "$([char]27)[$($String.Length)D" sequence. With Write-Host -NoNewLine I have to use "$([char]27)[$($String.Length+3)D".
5

To write to a file you can use a byte array. The following example creates an empty ZIP file, which you can add files to:

[Byte[]] $zipHeader = 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
[System.IO.File]::WriteAllBytes("C:\My.zip", $zipHeader)

Or use:

[Byte[]] $text = [System.Text.Encoding]::UTF8.getBytes("Enabling feature XYZ.......")
[System.IO.File]::WriteAllBytes("C:\My.zip", $text)

1 Comment

That is an awesome example!
5

There seems to be no way to do this in PowerShell. All of the previous answers are not correct, because they do not behave the way Write-Output behaves but more like Write-Host which doesn't have this problem anyway.

The closes solution seems to use Write-Host with the -NoNewLine parameter. You can not pipe this which is a problem generally, but there is a way to override this function as described in Write-Host => Export to a file, so you can easily make it accept the parameter for an output file. This is still far from a good solution. With Start-Transcript this is more usable, but that cmdlet has problems with native applications.

Write-Outputsimply can't do what you need in a general context.

EDIT 2023:

You can for craziness of it do something like this:

function log ($msg, [switch] $NoNewLine)
{
    $script:_msg+=$msg

    if ($NoNewLine)
    {
        Write-Host -NoNewline $msg
    }
    else
    {
        Write-Host $msg
        $script:_msg >> output.txt
        $script:_msg = ''
    }
}

Test:

log 'enabling feature xyx ' -NoNewLine; 1..3 | % { sleep 1; log . -NoNewLine }; log ' ok'; cat output.txt`
> enabling feature xyx ... ok

Comments

3

The problem that I hit was that Write-Output actually linebreaks the output when using using PowerShell v2, at least to stdout. I was trying to write an XML text to stdout without success, because it would be hard wrapped at character 80.

The workaround was to use

[Console]::Out.Write($myVeryLongXMLTextBlobLine)

This was not an issue in PowerShell v3. Write-Output seems to be working properly there.

Depending on how the PowerShell script is invoked, you may need to use

[Console]::BufferWidth =< length of string, e.g. 10000)

before you write to stdout.

1 Comment

Behaves like Write-Host, but worst. You can't pipe it to file for example.
3

I cheated, but I believe this is the only answer that addresses every requirement. Namely, this avoids the trailing CRLF, provides a place for the other operation to complete in the meantime, and properly redirects to stdout as necessary.

$c_sharp_source = @"
using System;
namespace StackOverflow
{
   public class ConsoleOut
   {
      public static void Main(string[] args)
      {
         Console.Write(args[0]);
      }
   }
}
"@
$compiler_parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler_parameters.GenerateExecutable = $true
$compiler_parameters.OutputAssembly = "consoleout.exe"
Add-Type -TypeDefinition $c_sharp_source -Language CSharp -CompilerParameters $compiler_parameters

.\consoleout.exe "Enabling feature XYZ......."
Write-Output 'Done.'

1 Comment

In pwsh (powershell core) Add-Type doesn't have the -CompilerParameters option, but you can do the same with other languages: python3 -c "import sys; print(sys.argv[1], end='')" "Enabling feature XYZ......."
3

The answer by shufler is correct. Stated another way: Instead of passing the values to Write-Output using the ARRAY FORM,

Write-Output "Parameters are:" $Year $Month $Day

or the equivalent by multiple calls to Write-Output,

Write-Output "Parameters are:"
Write-Output $Year
Write-Output $Month
Write-Output $Day
Write-Output "Done."

concatenate your components into a STRING VARIABLE first:

$msg="Parameters are: $Year $Month $Day"
Write-Output $msg

This will prevent the intermediate CRLFs caused by calling Write-Output multiple times (or ARRAY FORM), but of course will not suppress the final CRLF of the Write-Output cmdlet. For that, you will have to write your own cmdlet, use one of the other convoluted workarounds listed here, or wait until Microsoft decides to support the -NoNewline option for Write-Output.

Your desire to provide a textual progress meter to the console (i.e., "....") as opposed to writing to a log file, should also be satisfied by using Write-Host. You can accomplish both by collecting the message text into a variable for writing to the log and using Write-Host to provide progress to the console. This functionality can be combined into your own CPU for greatest code reuse.

5 Comments

I much prefer this answer over the others. If you're calling properties of objects, you can't enclose them in quotes so I used: Write-Output ($msg = $MyObject.property + "Some text I want to include" + $Object.property)
@Lewis You can certainly include object properties inside a string! Use the $() expression to surround any variable, e.g. "$($MyObject.Property) Some text I want to include $($Object.property)"
This may work in the specific example provided, but there is still an extra line feed produced by Write-Output, you just can't see it because it's the last thing written. Reasonable workaround, but not a solution. There may be something consuming the resultant output that can't handle the trailing newline.
Not correct. The solution can not be done with a single command.
This doesn't address the question. The log file output should show the operation that was about to be attempted so the failure can be seen and traced. Concatenation doesn't achieve that.
2

The following will place the cursor back at beginning of the previous row. It's up to you to place it in the right horizontal position (using $pos.X to move it sideways):

$pos = $host.ui.RawUI.get_cursorPosition()
$pos.Y -= 1
$host.UI.RawUI.set_cursorPosition($Pos)

Your current output is 27 spaces over, so $pos.X = 27 might work.

3 Comments

This has nothing to do with file output.
Its also not that bad. It can produce the correct output if you do $pos.X also. The problem is that if you pipe it to a file, two separate lines appear.
This is very useful for avoiding to have to use ANSI escape sequences when wanting to print on the same line.
2

You simply cannot get PowerShell to omit those pesky newlines... There is no script or cmdlet that does. Of course, Write-Host is absolute nonsense, because you can't redirect/pipe from it!

Nevertheless, you can write your own EXE file to do it which is what I explained how to do in Stack Overflow question How to output something in PowerShell.

6 Comments

Incorrect information. As Shay and Jay excellently answered, simply add -NoNewline as the first argument.
Maybe that's the case now @DavidatHotspotOffice but when I last touched a windows box (over a year ago) that didn't work, you couldn't redirect/pipe from Write-Host. To be fair I didn't have the slightest bit of patience for POSH or .NET, I quit after a few months and went back to unix land. funny
@DavidatHotspotOffice - Actually, he's correct. There's no "NoNewLine" argument for Write-Output, which is what the original question was asking about. There are some good reasons, it seems, for using Write-Output - so this answer makes sense. jsnover.com/blog/2013/12/07/write-host-considered-harmful
Downvoted because question is asking for a solution "in PowerShell". Writing an external EXE is not "In PowerShell".
@SlogmeisterExtraordinaire It's not possible in PowerShell therefore my answer is reasonable. Your just downvoting because your so sad that you have to work with the worlds worst operating system which has the worlds worst shell.
|
2

Write-Host is terrible, a destroyer of worlds, yet you can use it just to display progress to a user whilst using Write-Output to log (not that the OP asked for logging).

Write-Output "Enabling feature XYZ" | Out-File "log.txt" # Pipe to log file
Write-Host -NoNewLine "Enabling feature XYZ......."
$result = Enable-SPFeature
$result | Out-File "log.txt"
# You could try{}catch{} an exception on Enable-SPFeature depending on what it's doing
if ($result -ne $null) {
    Write-Host "complete"
} else {
    Write-Host "failed"
}

1 Comment

Depending on your needs for indicating progress, there's also Write-Progress.
2

A simplification to FrinkTheBrave's response:

[System.IO.File]::WriteAllText("c:\temp\myFile.txt", $myContent)

2 Comments

This doesn't answer the question at all.
But it is exactly that what I searched for and what I expected from the title of the question.
2

Personally, I just use something like this:

write "the user $($user.firstname) is online"

If I don't use $(), only $user is interpreted, not $user.firstname.

Comments

1
$host.UI.Write('Enabling feature XYZ.......')
Enable-SPFeature...
$host.UI.WriteLine('Done')

1 Comment

Doesn't work: you can't pipe this.
1

I'm not an expert by any means, but why not this:

Write-Output "hello" | ForEach-Object {  $PSItem.Trim() } | Do-Whatever

This maintains the pipeline semantics, but it just trims the new line characters before passing it on down the pipeline to whatever you need to do next. If that is writing to a file, so be it. If that is writing to the host, you can do that, but if you do write it to the host, remember to use | Write-Host -NoNewline

As per my comment below: "I see why my answer won't work.. PowerShell inevitable appends a new line character as part of its piping semantics when piping to external programs. See this: github.com/PowerShell/PowerShell/issues/5974. Therefore, when I pass the trimmed text down the pipeline, the new line character will reappear in the input."

1 Comment

Ok I see why my answer won't work.. Powershell inevitable appends a new line char as part of it's piping semantics when piping to external programs. See this: github.com/PowerShell/PowerShell/issues/5974 Therefore when I pass the trimmed text down the pipeline, the new line char will re-appear in the input.
0

It may not be terribly elegant, but it does exactly what the OP requested. Note that the ISE messes with standard output, so there will not be any output. In order to see this script work, it can't be run within the ISE.

$stdout=[System.Console]::OpenStandardOutput()
$strOutput="Enabling feature XYZ... "
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
Enable-SPFeature...
$strOutput="Done"
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
$stdout.Close()

2 Comments

Not correct. If you put that to a file and pipe its output nothing appears.
Piping to a file was not something that the OP requested. And yes, [System.Console] cannot be redirected to a file.
0

The simplest way with in-line concatenation. And while moving across to 'Write-Output' instead; for example., two tab characters (string) and then a literal/verbatim (string):

Write-Output ("`t`t" + '${devArg}')

Comments

-1

Desired output:

Enabling feature XYZ......Done

You can use the below command

$a = "Enabling feature XYZ"

Write-output "$a......Done"

You have to add a variable and a statement inside quotes.

1 Comment

Write-Output is preferred for putting objects out to the pipeline. For text display, Write-Host is frequently use and more recently Write-Information is used to write to the Information stream.
-2

From the link in the comments, that answer includes:

Write-Output "Some text $( $var.Name )"

which worked very well for me. The $( ) is not redundant if you need to ExpandProperty to get the individual value of Name, otherwise my output was this instead of the resolved value:

@{Name=Name; Address=Address; City=City}.Name

Comments

-3

You can absolutely do this. Write-Output has a flag called "NoEnumerate" that is essentially the same thing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.