Reputation: 165
I would like to read data from csv or another txt files. Data should been read only from row 1 and few columns on row 1 and save them to variables and after saving delete the row. Now I have done it like this:
Get-ChildItem -Path C:\path | ForEach-Object -Process {
$YourContent = Get-Content -Path $_.FullName
$YourVariable = $YourContent | Select-Object -First 1
$YourContent | Select-Object -Skip 1 | Set-Content -Path $_.FullName
My problem is that my variable prints out like this :
Elvis;867.5390;[email protected]
So I would like to save each variable to its own column. Example what csv could look:
Elvis | 867.5309 | [email protected] Sammy | 555.1234 | [email protected]
Upvotes: 0
Views: 599
Reputation: 165
Thanks for the answers!
I try to clarify a bit more what i was trying to do. Answers might do it already, but I'm not yet that good in Powershell and learning still a alot.
If I have csv or any other txt file, i would want to read the first row of the file. The row contains more than one piece of information. I want also save each piece of information to Variables. After saving information to variables, I would like to delete the row.
Example:
Car Model Year
Ford Fiesta 2015
Audi A6 2018
In this example, i would like to save Ford, Fiesta and 2015 to variables (row 1)($Card, $Model, $Year) and after it delete the row. The 2nd row should not be deleted, because it is used later on
Upvotes: 0
Reputation: 7489
here's one way to do what i think you want.
Code:
$FileName = "$env:TEMP\Pimeydentimo.txt"
# create a file to work with
@'
Alfa;123.456;Some unwanted info;[email protected]
Bravo;234.567;More info that can be dropped;[email protected]
Charlie;345.678;This is also ignoreable;[email protected]
'@ | Set-Content -LiteralPath $FileName
$InStuff = Get-Content -LiteralPath $FileName
$TempObject = $InStuff[0] |
ConvertFrom-Csv -Delimiter ';' -Header 'Name', 'Number', 'DropThisOne', 'Email' |
Select-Object -Property * -ExcludeProperty DropThisOne
$InStuff[1..$InStuff.GetUpperBound(0)] |
Set-Content -LiteralPath $FileName
$InStuff
'=' * 30
$TempObject
'=' * 30
Get-Content -LiteralPath $FileName
output ...
Alfa;123.456;Some unwanted info;[email protected]
Bravo;234.567;More info that can be dropped;[email protected]
Charlie;345.678;This is also ignoreable;[email protected]
==============================
Name Number Email
---- ------ -----
Alfa 123.456 [email protected]
==============================
Bravo;234.567;More info that can be dropped;[email protected]
Charlie;345.678;This is also ignoreable;[email protected]
Upvotes: 1
Reputation: 1660
Use Import-Csv
instead of Get-Content
:
Import-Csv file.csv -Delimiter ";" -Header A, B, C
Upvotes: 2