Cataster
Cataster

Reputation: 3521

Add-Content not appending to last output

I want to append an output to the last console output.

  $r = write-output "$server - $db"
  $r
  Add-Content $r -Value " : Success!"

essentially im trying to get this output:

server - db : Success!

on MS docs, https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-content?view=powershell-6

the examples assume a file is being used. isnt there a way to append to console output?

if i use -PassThru it outputs on next line, which i dont want

server - db

: Success!

Upvotes: 0

Views: 495

Answers (2)

Mark Wragg
Mark Wragg

Reputation: 23355

Add-Content is specifically for adding content to an external resource such as a file. If you just want to append to a string you can just do this:

$r = "$Server - $DB"
$r
$r = $r + " : Success"
$r 

Or you could use string interpolation like this:

$r = "$r : Success"

And anything you do that isn't sent somewhere else is going to print to the console by default, so you don't need to use Write-Output or even update the variable if your only goal is to get it on the screen, you can just put this on a line on its own:

"$r : Success"

If your goal is to write some text to the console and then later append some text to the same line, you can do that with Write-Host:

$r = "$Server - $DB"
Write-Host $r -NoNewLine
Write-Host " : Success"

Upvotes: 4

jrider
jrider

Reputation: 1640

All you need to do is concatenate the string.

The following example should give you the output desired:

$r = write-output "$server - $db"
$r += " : Success!"
$r

Upvotes: 1

Related Questions