0
votes

I have the following script.

$cols = Get-MyColumns # returns "a","b","c",...
$cols2 = $cols, @{n='x'; e={"0"}} # Add a new column
import-csv test.csv | select -property $cols2

However the script gets the following error.

select : Cannot convert System.Object[] to one of the following types {System.String, 
System.Management.Automation.ScriptBlock}.
At line:1 char:xx
+ Import-Csv test.csv | select -Property $cols2
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupportedException
    + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

The string array cannot be concatenated with the customized column definition. What's the workaround of it?

1

1 Answers

1
votes

In you calculated property you need to delimit the Name and Expression with a semi colon. You also need to combine the "fields" so they are passed as one-dimensional array to the -Property parameter.

select -Property ($cols + @{n='x';e={0}})

Property expects a single string or an array. Changing the definition for $cols would also have worked

$cols = "a","b","c",@{n='x';e={"0"}}

If you don't care about the value of the new column you can just put in whatever to create a null column.

$cols = "a","b","c","doesnotexist"

For example:

a b c doesnotexist
- - - ------------
1 2 3             
4 5 6