Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to access row and column in CSV file 1

Status
Not open for further replies.

JustScriptIt

Technical User
Oct 28, 2011
73
0
0
US
I have powershell code,

Code:
$file = Import-CSV C:\PS\IP_list.csv
Write-Output $file

And I have output


I am unable to figure out how to access 1st row, 2nd column, or 2nd row, 4th column.

Help!
 

Once you've imported using Import-CSV, you can use a ForEach loop to cycle through each row.
Code:
$file = Import-CSV C:\PS\IP_list.csv
ForEach ($record in $file){
Write-Host "Lower IP: $record.lower_ip"
Write-Host "Upper IP: $record.upper_ip"
Write-Host "Group Name: $record.group_name"
Write-Host "Group ID: $record.group_id"
}

Do you have your Tek-Tips.com Swag? I've got mine!

Stop by the new Tek-Tips group at LinkedIn.
 
Try this:
Code:
$file = Import-CSV C:\PS\IP_list.csv
ForEach ($record in $file){
$lowerIP = $record.lower_ip
$upperIP = $record.upper_ip
$groupName = $record.group_name
$groupID = $record.group_id

Write-Host "Lower IP: $lowerip"
Write-Host "Upper IP: $upperip"
Write-Host "Group Name: $groupname"
Write-Host "Group ID: $groupid"
}

You can also modify the Import-CSV to target specific lines, such as
Code:
$file = Import-CSV C:\PS\IP_list.csv | ?{$_.lower_ip -eq "10.251.10.1" -and $_.upper_ip -eq "10.251.10.254"}

Do you have your Tek-Tips.com Swag? I've got mine!

Stop by the new Tek-Tips group at LinkedIn.
 
I think I am not explaning clearly.

I am looking to create a powershell script that does the following
1. Reads an IP address from an MS SQL database
2. Opens the CSV file of the IP addresses
3. Determine which range the IP address falls in
4. Perform the necessary updates based on which range the IP address falls in

In other words, I need to read the entire CSV file.

Can you point me in the right direction?
 
Your very first line of code reads in the entire file. My suggested code allows you to loop through each row.
I don't have time to try and do all the work for you. There is plenty of resources online for dealing with SQL access as well as looping through arrays.

Do you have your Tek-Tips.com Swag? I've got mine!

Stop by the new Tek-Tips group at LinkedIn.
 
Well, I appreciate your help, I didn't mean to upset you :-(
 
By the way, I figured out the solution

Code:
$file_line = @()
$file_multi = @()
$file = Get-Content C:\PS\IP_list.csv
foreach ($i in $file){
    $file_line += $i.split("`n")
}

foreach ($j in $file_line){
    $file_multi += ,@($j.split(",")) 
}

Write-output $file_multi[1][3]
Write-output `n
Write-output $file_line
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top