Test File
Read the complete CSV file contents into a string:
Code:
$CSV2String = Get-Content -path "C:TempTest-File.csv"
write-host "[$CSV2String]"
Output:
[User001, DFdP, FmpD User002, weKC, v85F User003, va2W, gwkE User004, fBBn, dhey User005, cUmC, 9vpK User006, xESN, FDTc User007, FL4p, EpgS User008, 9EV9, GBTc User009, NtPA, NGDN User010, FKcY, 1NCL]
Read the CSV file line by line. Print each of the CSV file line in its CSV format
Code:
$CSV2String = Get-Content -path "C:TempTest-File.csv"
foreach ($line in $CSV2String) {
write-host "[$line]"}
Output:
[User001, DFdP, FmpD]
[User002, weKC, v85F]
[User003, va2W, gwkE]
…
Remove any spaces in CSV data
Code:
$CSV2String = Get-Content -path "C:TempTest-File.csv"
foreach ($line in $CSV2String) {
# use below code if you need to replace any spaces in the data of csv file
$line_text = $line -replace " ", ""
write-host "[$line_text]"}
Output:
[User001,DFdP,FmpD]
[User002,weKC,v85F]
[User003,va2W,gwkE]
…
Print each of the data in CSV file line after removing spaces:
Code:
$CSV2String = Get-Content -path "C:TempTest-File.csv"
foreach ($line in $CSV2String) {
# use below code if you need to replace any spaces in the data of csv file
$line_text = $line -replace " ", ""
$text = $line_text -split ","
foreach($string in $text) {
Write-Host "[$string]"
}
}
Output:
[User001]
[DFdP]
[FmpD]
[User002]
[weKC]
…
Operate on Data in CSV fields
Code:
foreach ($line in $CSV2String) {
# use below code if you need to replace any spaces in the data of csv file
$line_text = $line -replace " ", ""
$text = $line_text -split ","
foreach($string in $text) {
$Username = $text[0]
$Data1 = $text[1]
$Data2 = $text[2]
if ($Username -eq ‘User001’) {
Write-Host "Processing [$Username]: User Data is: [$Data1] and [$Data2] "
}
}
}
Output:
Processing [User001]: User Data is: [DFdP] and [FmpD]
Processing [User001]: User Data is: [DFdP] and [FmpD]
Processing [User001]: User Data is: [DFdP] and [FmpD]