1

Using Write-Host in a $() subexpression always outputs to the beginning of a string, regardless of its position.

For example:

"This is $(Write-Host 'now at the beginning' -NoNewline)"

Outputs:

now at the beginningThis is

Other cmdlets work as expected here (e.g. "Today is $((Get-Date).DayOfWeek)", Today is Friday).

How is Write-Host different?

1
  • Write-Host write string to host and not return anything. Commented Oct 1, 2016 at 4:09

1 Answer 1

3

It doesn't "output to the beginning of the string", it writes to the host twice, in 'backwards' order.

  1. "abc $()" is a string literal that includes a sub-expression.
  2. Calculating what the string is, means evaluating the $()
  3. Evaluating the $() writes to the screen now at the beginning and returns nothing
  4. Now the string literal is "abc"
  5. Now "abc" is written to the screen now at the beginningabc

This is not doing what you suggest:

  1. "abc $(write-host 'hi')"
  2. "hiabc"
  3. write to screen.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.