1

I have a CSV file containing two columns:server name with domain and date

servername.domain.domain.com,10/15/2018 6:28
servername1.domain.domain.com,10/13/2018 7:28

I need to remove the fully qualified name so it only has the shortname and I need to keep the second column so it looks as is like below either by sending to a new CSV or somehow removing the domain inplace somehow. Basically I want the second column untouched but I need it to be included when creating a new CSV with the altered column 1.

servername,10/15/2018 6:28
servername1,10/13/2018 7:28

I have this:

Import-Csv "filename.csv" -Header b1,b2 |
    % {$_.b1.Split('.')[0]} |
    Set-Content "filename1.csv"

This works great, but the problem is the new CSV is missing the 2nd column. I need to send the second column to the new CSV file as well.

1 Answer 1

2

Use a calculated property to replace the property you want changed, but leave everything else untouched:

Import-Csv 'input.csv' -Header 'b1', 'b2' |
    Select-Object -Property @{n='b1';e={$_.b1.Split('.')[0]}}, * -Exclude b1 |
    Export-Csv 'output.csv' -NoType

Note that you only need to use the parameter -Header if your CSV data doesn't already have a header line. Otherwise you should remove the parameter.

If your input file doesn't have headers and you want to create the output file also without headers you can't use Export-Csv, though. Use ConvertTo-Csv to create the CSV text output, then skip over the first line (to remove the headers) and write the rest to the output file with Set-Content.

Import-Csv 'input.csv' -Header 'b1', 'b2' |
    Select-Object -Property @{n='b1';e={$_.b1.Split('.')[0]}}, * -Exclude b1 |
    ConvertTo-Csv -NoType |
    Select-Object -Skip 1 |
    Set-Content 'output.csv'
Sign up to request clarification or add additional context in comments.

1 Comment

Genius! Thank you so much Ansgar! It worked like a charm. You are correct the csv didn't have headers, it's an automated csv that gets generated from a software product and doesn't contain headers. One quick question the new csv now contains b1 and b2 on the top of each column on the new csv, if there any way to not include that with this command? I can do a search to how to remove that whole row so no big deal if not. This is awesome thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.