I have a multiline here-string of Visual Studio component IDs. I split it on newline, add --add before each ID, and join the results. It looks right in the terminal, but running the same code from a .ps1 file only appears to print one entry. What could cause that?
Why does my PowerShell code work in the terminal but not in a script?
Asked by
y83~muxstate_214
Answers
Check the line endings. If the script file uses Windows CRLF endings, splitting on just the line feed with -split "`n" leaves a carriage return at the end of each ID. When printed, those carriage returns can move the cursor back to the start of the line and make the output look overwritten.
Try -split '\r?\n' instead. That handles both LF and CRLF line endings, so the same script is less dependent on how the file was saved.
Reply to this answer
You could skip the here-string and split entirely. Put the IDs directly in an array, with each ID as a quoted string on its own line, then keep the part that adds --add and joins the entries. That avoids carrying line-ending characters into the values.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Tivlet.5m:
If the file is definitely CRLF, -split "`r`n" works too. The regex version is handy if the file might use either style.