Reputation: 917
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()';
}
Upvotes: 0
Views: 317
Reputation: 174485
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
Upvotes: 2
Reputation: 96
What you do within your code is:
[object] $x = 'abc', 'def'
==> The type of 'abc' and 'def' is [System.String]. Because you comma seperated them PowerShell does automatically create a list. So after executing that line $x is a System.Object[]. Index 0 and 1 contains [System.String].
$x = $null;
==> Now you define $null as the value for $x. So you are removing the value. The type of $x is now undefinded. You can set the value 123 then $x will become type System.Int32. You can redefine a string and so on.
Within your for-loop you use
$x += 'somestring' + $addingSomeStuff + 'otherstring'
==> The result here is that within the first Iteration of the for-loop PowerShell will assign a String to $x. So the type of $x will be [System.String]. In the next iterations the += operator adds additionally content to the value of $x, which is still [System.String]
Don't set $x to $null. Because you'll loose the type information. For more information read about the PowerShell Extended Type System.
The following snippet works. Hope that helps.
############################################
# The following was not part of your post #
# I added it to get it run in general #
$numberOfColumns = 2
$NamesOfColumns = 'Column1', 'Column2'
############################################
[object] $x = 'abc','def';
# don't set $x to $null
# define an empty list instead ;-)
$x = @()
for ($i = 0; $i -lt $numberOfColumns; $i++) {
$x += '$_.' + $NamesOfColumns[$i] + '.Trim()';
}
Upvotes: 3