Question:
i’m importing a csv and i would like to add a column to it (with the result based off of the previous columns)
my data looks like this
1 2 3 |
host address,host prefix,site 10.1.1.0,24,400-01 |
i would like to add a column called “sub site”
so I wrote this module but the problem is, the actual ending object is an array instead of string
1 2 3 4 5 6 7 8 |
function site { Param($s) $s -match '(\d\d\d)' return $Matches[0] } $csv = import-csv $file | select-object *,@{Name='Sub Site';expression= {site $_.site}} |
if I run the command
1 2 3 4 5 6 7 |
PS C:\>$csv[0] Host Address :10.1.1.0 host prefix :24 site :400-01 sub site : {True,400} |
when it should look like
1 2 3 4 5 6 7 |
PS C:\>$csv[0] Host Address :10.1.1.0 host prefix :24 site :400-01 sub site : 400 |
EDIT: I found the solution but the question is now WHY.
If I change my function to $s -match "\d\d\d" |out-null
I get back the expected 400
Answer:
Good you found the answer. I was typing this up as you found it. The reason is because the -match
returns a value and it is added to the pipeline, which is all “returned” from the function.
For example, run this one line and see what is does:
1 2 |
"Hello" -match 'h' |
It prints True
.
Since I had this typed up, here is another way to phrase your question with the fix…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function site { Param($s) $null = $s -match '(\d\d\d)' $ret = $Matches[0] return $ret } $csv = @" host address,host prefix,site 10.1.1.1,24,400-01 10.1.1.2,24,500-02 10.1.1.3,24,600-03 "@ $data = $csv | ConvertFrom-Csv '1 ==============' $data | ft -AutoSize $data2 = $data | select-object *,@{Name='Sub Site';expression= {site $_.site}} '2 ==============' $data2 | ft -AutoSize |