Costa Zachariou Costa Zachariou - 3 months ago 7
PowerShell Question

Object variable changes to a string

I have a variable set as an object as follows:

[object] $x = 'abc','def';


If I view what $x is now, I get:

acb
def


Now my problem is when I set $x to $null and then try to rather set $x from a loop using += after reading the file it change $x type to a string and if I view what $x is now it gives me:

abcdef


instead of:

abc
def


How do I go about it to keep the variable as an object rather then a string?

Below is just a sample to get the idea:

[object] $x = 'abc','def';

$x = $null;

for ($i = 0; $i -lt $numberOfColumns; $i++) {
$x += '$_.' + $NamesOfColumns[$i] + '.Trim()';
}

Answer

In the underlying type system (.NET CTS), [object] is the base class for any object, and is the most vague type description you can give any variable - it doesn't convey any specialized meaning at all.

As mentioned in @PatM0's answer, the best solution here is to initialize the variable value with the array subexpression operator (@()) before using += :

$x = @()

If you really want to force a variable to be a collection type, use the array or psobject[] type accelerators:

PS C:\> [array]$x = 'abc','def'
PS C:\> $x = $null
PS C:\> $x += 'abc'
PS C:\> $x += 'def'
PS C:\> $x
abc
def
PS C:\> [psobject[]]$x = 'abc','def'
PS C:\> $x = $null
PS C:\> $x += 'abc'
PS C:\> $x += 'def'
PS C:\> $x
abc
def

Compare with [object]:

PS C:\> [object]$x = 'abc','def'
PS C:\> $x = $null
PS C:\> $x += 'abc'
PS C:\> $x += 'def'
PS C:\> $x
abcdef
Comments