Why does my PowerShell code behave differently in a script than in the terminal?

0
3
Asked By QuietMaple42 On

This PowerShell command produces the expected single-line argument string when entered interactively, but when the same code runs from test.ps1, it only returns the final entry, --add Microsoft.VisualStudio.Component.WinXPStudioExtension. The script stores several Visual Studio component IDs in a here-string, splits the string on a newline, prefixes each item with --add, and joins the results with spaces. Why does the script produce different output, and what is the best way to build this argument list?

3 Answers

Answered By LunarPine58 On

A more portable option is to split on `r?n`, which handles both Windows and Unix-style line endings without hardcoding one platform's newline sequence. For example: `$id = @'... '@ -split 'r?n'`.

Answered By CedarOrbit7 On

The here-string in a Windows script uses CRLF line endings, but your split only looks for LF. Split on both characters with `-split "`r`n"` if you know the file uses Windows line endings.

Answered By BrightHollow31 On

You can avoid the here-string and splitting entirely by defining the values as an array. Then format each item directly: `$id = [string[]]@('Microsoft.VisualStudio.Component.CoreEditor','Microsoft.VisualStudio.Workload.Azure','Microsoft.VisualStudio.Workload.Data','Microsoft.VisualStudio.Workload.DataScience','Microsoft.VisualStudio.Workload.ManagedDesktop','Microsoft.VisualStudio.Workload.NativeCrossPlat','Microsoft.VisualStudio.Workload.NativeDesktop','Microsoft.VisualStudio.Workload.NativeGame','Microsoft.VisualStudio.Workload.NativeMobile','Microsoft.VisualStudio.Workload.NetCrossPlat','Microsoft.VisualStudio.Workload.NetWeb','Microsoft.VisualStudio.Workload.Node','Microsoft.VisualStudio.Workload.Python','Microsoft.VisualStudio.Workload.Universal','Microsoft.VisualStudio.Workload.VisualStudioExtension','macos','Microsoft.VisualStudio.Component.WinXP');($id | ForEach-Object { "--add $PSItem" }) -join ' '`. This is clearer and avoids newline-related issues.

MistyQuill64 -

Using `ForEach-Object` instead of the `%` alias also makes the script easier to read. Aliases are convenient interactively, but full cmdlet names are generally better in scripts.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.