Get Input from CSV Files

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 7 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
venkirocs
Posts: 3
Last visit: Sat Dec 07, 2019 6:06 am

Get Input from CSV Files

Post by venkirocs »

Hi,

For some bulk activities, I will get the input data through a CSV. I used a Button, when the button is clicked the OpenFileDialog will pop-up and capture the filename. Next I use the Import-Csv command to fetch the data from that file. Then will use the Foreach loop to process each object in the file.

Currently I have to hardcode the header of the csv file for the powershell commands to process the task.
e.g if the filename is rename.csv and the header consists of "Oldname" and "newname" as columns, i would code as below.

$data = Import-Csv -path C:\temp\rename.csv
foreach($pc in $data)
{
Rename-Computer -ComputerName $pc.Oldname -NewName $pc.newname -DomainCredential $cred
}

Because of this I have to insists the tool users to maintain the csv file and its headers. So for all the tools I create I would have to insists the users

is there a way to dynamically obtain the header of the csv, so the users can give any column header
User avatar
owinsloe
Posts: 161
Last visit: Tue Apr 16, 2024 8:36 pm
Been upvoted: 1 time

Re: Get Input from CSV Files

Post by owinsloe »

$data[0].psobject.properties.name will give you the ordered col headers
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Get Input from CSV Files

Post by jvierra »

To rename the columns in a CSV with columns:

import-csv test.csv -header oldname,newname | select * -skip 1
User avatar
venkirocs
Posts: 3
Last visit: Sat Dec 07, 2019 6:06 am

Re: Get Input from CSV Files

Post by venkirocs »

Thank you all.
This topic is 4 years and 7 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked