0

Say I have the following code:

$roles = @("first", "second", "third")

$roles = $roles | Where-Object {$_ -ne "second"}       
$roles += "last"

$roles

This will result in the following output:

first
third
last

Just what I would expect. But if I take out the "thrid" element of the array, then it performs oddly. Here is the code I run (in VS Code):

$roles = @("first", "second")

$roles = $roles | Where-Object {$_ -ne "second"}       
$roles += "last"

$roles

This results in the following:

firstlast

(all on one line)

Is Powershell changing my variable to be a string when I pull out the second to last array? If so, how do I stop it from doing that? If not, what is going on here?

Why is my array all of a sudden working like a string?

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 2
    You can wrap all the expression in [`@(...)`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2#array-subexpression-operator--) to force an array – Santiago Squarzon May 06 '22 at 23:33
  • 1
    `($roles | Where-Object {$_ -ne "second"}).GetType()` will reveal what's going on. Why would you expect a scalar element of an array to, itself, be an array? That you are operating on an array does not mean all of those operations produce arrays, too. If you want them to, though, you can make it so with the `@()` operator you're already using, as that's what it's for. – Lance U. Matthews May 06 '22 at 23:43

0 Answers0