import and export csv file in powershell - powershell

i have a csv file "emp.csv" with following information.
empid status
1 t
2 a
3 t
4 t
5 a
I need empid and status of employees having status="t" and the output should be in "res.csv" file

For this, you'll first want to import the existing data with Import-Csv - but since your file is technically a TSV (tab-separated instead of comma-separated), make sure you specify this with -Delimiter "`t":
$employeeStatusData = Import-Csv .\path\to\emp.csv -Delimiter "`t"
Import-Csv will parse the input file and store the resulting objects in $employeeStatusData. To filter these object based on the value of the status property/column, use Where-Object:
$filteredEmployeeData = $employeeStatusData |Where-Object status -eq 't'
Now that you have the relevant rows selected, you can export the data again with Export-Csv:
$filteredEmployeeData |Export-Csv .\path\to\res.csv -Delimiter "`t" -NoTypeInformation

Related

Merge two columns in CSV file from command line / PowerShell

I have a CSV file where either column "EAN" (col. 9) or column "UPC" (col. 10) is set (some lines with both). What I need is a CSV where both are combined into one column, something like
if EAN <> "" use EAN else use UPC
to be put into a batch/PowerShell file. Additionally I need to keep col. 11, everything else can be discarded. The output file only has to contain two columns, either EAN or UPC plus stock level. Any help would be appreciated.
The original CSV is semicolon seperated with possible empty values, but no quoted values with the seperator or newline characters.
Example input:
company;dept;sku;desc;secsku;unit;size;year;ean;upc;stock;exact(CRLF)
Stack;Overflow;000-000;Question0;00;pcs;XL;2021;1111111111111;;1;6(CRLF)
Overflow;Stack;000-001;Question1;01;pcs;L;2021;;222222222222;1;9(CRLF)
The output should look like:
ean;stock(CRLF)
1111111111111;1(CRLF)
222222222222;1(CRLF)
One way is to use a calculated property:
# import the source csv file
Import-Csv -Path 'D:\Test\test.csv' -Delimiter ';' |
# select only two of its properties where 'ean' is a calculated property
Select-Object #{Name = 'ean'; Expression = {if(![string]::IsNullOrWhiteSpace($_.ean)) {$_.ean} else {$_.upc}}}, stock |
# output to a new CSV file
Export-Csv -Path 'D:\Test\updated.csv' -Delimiter ';' -NoTypeInformation
Another way of doing that (less concise) is by using a PsCustomObject
# import the source csv file
Import-Csv -Path 'D:\Test\test.csv' -Delimiter ';' |
# loop through the data
ForEach-Object {
# output an object with two properties
[PsCustomObject]#{
ean = if(![string]::IsNullOrWhiteSpace($_.ean)) { $_.ean } else { $_.upc }
stock = $_.stock
}
} |
# output to a new CSV file
Export-Csv -Path 'D:\Test\updated.csv' -Delimiter ';' -NoTypeInformation

How to handle dynamic columns for CSV file using Import-csv in PowerShell

CSV file does not have headers, Column may differ each time.
I want to compare with first column of csv file, but while exporting I would display the full row.
$getErrorCodes= {102,103}
CSV FILE( No headers)
101,101,101
102,102,102
Here is my code
Import-Csv $CSVFile -Header col1 | Where-Object {!($getErrorCodes.Contains($_.col1)) } | Export-Csv "resultfile.csv"
Current output
101
Expected output
101,101,101
For dynamic header, I used like this.
Dynamically will change $headers variable accordingly column count on csv.
$headers = 'Col1,Col2,Col3'
$headercolumns = $headers.ToString().Split(",")
Import-Csv $CSVFile -Header $headercolumns | Where-Object {!($getErrorCodes.Contains($_.col1)) } | Export-Csv "resultfile.csv"

Need 3 digits in column in a CSV-file

I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:
Name, Count
1,34
3,55
15,66
103,99
etc.
So far so good...
My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".
So the CSV-file need to look like this:
Name, Count
001,34
003,55
015,66
103,99
etc.
How can I do this formatting using "Export-CSV"?
Please help I'm stuck here..
There are several ways to apply the changes to the csv file.
Read/Import to a variable, change name, Export-Csv variable
$Csv = Import-Csv .\Sample.csv
$Csv | ForEach-Object{ $_.Name = $_.Name.PadLeft(3,'0') }
$Csv | Export-Csv .\NewSample.csv -NoTypeInformation
Do the same on the fly with a calculated property reusing the same header/property name.
Import-Csv .\Sample.csv |
Select-Object #{n='Name';e={$_.Name.PadLeft(3,'0')}},Count|
Export-Csv .\NewSample2.csv -NoTypeInformation
Use the -f ( format ) operator with variable
i.e.
[int] $int = 25;
"{0:D3}" -f $int
Here 3 is a number of digits and Output will be :
025

Selecting columns from flat file in power shell with no column name

I am new to power shell ,and I have the below format (pipe delimiter) with no column name:
01|1|06/28/2017 00:00:00|06/28/2017 00:00:00
I want to choose the third or any column from this format,I have tried the below code :
$columns=(Get-Content $filepath | Out-String | select -Skip 2 -First 1).Split("|")
but it is not working can any one help please.
Use Import-CSV with -Header and -Delimiter specified; that way, you get a structure (PSCustomObject[]) with attributes that you can reference directly and meaningfully. For example,
$EntryList = Import-CSV -Path $FilePath -Header ID,Type,StartTime,EndTime -Delimiter '|'
gets you an array of PSCustomObjects, where each object has the indicated fields. You can then (for example) refer to $EntryList[$n].ID, $EntryList[$n].StartTime, and so on.

Manipulate CSV files with Powershell (generate column for hashkey)

I have a CSV file with about 10 columns separated with a ; (semicolon). I would like to add another column which generates a hashkey for the first columns value.
Is there a possibility in Powershell to do this? Also are there short haskeys (up to 10 to 15 chars)?
Example:
Old:
10000;value2;value3....
New:
HashkeyOf10000;1000;value2;value3...
You can use a calculated property for adding a column to a CSV:
$csv = 'C:\path\to\your.csv'
(Import-Csv $csv -Delimiter ';') |
select -Property #{n='Hashkey';e={Calc-Hash $_.A}},* |
Export-Csv $csv -Delimiter ';' -NoType
Replace Calc-Hash with the actual name of your hash function and A with the actual name of the first column of your CSV.
The parentheses around Import-Csv are required to ensure that reading the file is completed before writing the output starts.