powershellline-breakspowershell-ise

Powershell Write-Host Line Breaks In Different Scripts


I have 2 different scripts with line breaks. One of them won't make line breaks without "`n" at the end of each line. See this example with and without the "`n".

enter image description here

But other scripts work without the "`n" tag.

write-host "
This is a test message

This is 2 lines down.
"

Output:

This is a test message

This is two lines down.

What makes them different where they do or don't need the "`n". They are both .ps1 extensions. And, as you can see, they are at the start of the script. Why do some scripts show the line breaks with the "`n" and others don't need it?


Solution

  • So after working with some friends here we found that issue seems to be the way that ISE reads the file when it is made. If you make a new .ps1 file on ISE it does not notice the script items like Write-Host or functions as a full block of function. This would be denoted by the collapse (+/-) symbol next to that line of code. This means you need to add the `n code to end of each Write-Host line break for it to identify it.

    Example: This is a .ps1 file started and made in ISE:

    File started in ISE

    Now the easiest way to fix this is to take the code and start it over in a Notepad file. Copy your code into a new file on Notepad and then save it as a .ps1. When you do this your Write-Host line breaks will not require the `n as it is being read by ISE correctly.

    Example: This is a .ps1 file started and made in Notepad:

    File started in Notepad

    I am not sure why there is a there is an error with ISE reading .ps1 files when made in ISE and reading line breaks with Write-Host. It may have something to do with no longer being supported. Suggestion would be to move over to VS code with Powershell and code with that. Very strange issue but glad I understand now.