M
M
myxz2021-09-28 09:25:14
PowerShell
myxz, 2021-09-28 09:25:14

How to remove extra characters from a csv file in a specific column using PowerShell?

Dear experts, tell me there is a csv file of this kind:

ExternalEmailAddress,FirstName,LastName,DisplayName,StreetAddress,City,StateorProvince,PostalCode,Phone,MobilePhone,Pager,HomePhone,Company,Title,OtherTelephone,Department,CountryOrRegion,Fax,Initials,Notes,Office,Manager
[email protected],Анастасія,Бурав,Анастасія Бурав,,,,,,,,,test,менеджер з персоналу,,Офіс  Департамент HR  відділ рекрутингу,,,,,,,,,
[email protected],Ада,Сорокін,Ада Сорокін,,,,,,,,,test,керуючий магазином 3 категорії,,Київ  Bublik-13 Київ  (В-13)управління,,,,,,,,,
[email protected],Advertisement,Manager,Advertisement Manager,,,,,,,,,test,,,,,,,,,,,,


According to the task, take a CSV FILE, pull out 2 columns $Title and $Departmen if in these tables for each line over 50 characters cut and write. Putting the variables in place

If, ​​for example, $Title is empty and $Department is not, then write an empty Title and check if $Departme does not exceed 50 characters, if not, also write it in its place; if it exceeds, truncate to 50 characters and write to a file
If the cell is empty, leave it empty, do this:


# Указываем исходный файл
$impfile = "C:\Laba\kniga123.csv"
# Импортируем файл, указывая в качестве разделителя символ точку с запятой
$users =Import-Csv -Path $impfile -Delimiter ","
#Запускаем цикл и парсим каждую строчку
$(foreach ($user in $users)
{
#Считыаем данные из каждой ячейки матрицы в свою переменную
$ExternalEmailAddress = $user.ExternalEmailAddress;
$FirstName = $user.FirstName;
$LastName = $user.LastName;
$DisplayName = $user.DisplayName;
$StreetAddress = $user.StreetAddress;
$City = $user.City;
$StateorProvince = $user.StateorProvince;
$PostalCode = $user.PostalCode;
$Phone = $user.Phone;
$MobilePhone = $user.MobilePhone;
$Pager = $user.Pager;
$HomePhone = $user.HomePhone;
$Company = $user.Company;
$Title = $user.Title;
$OtherTelephone = $user.OtherTelephone;
$Department = $user.Department;
$CountryOrRegion = $user.CountryOrRegion;
$Fax = $user.Fax;
$Initials = $user.Initials;
$Notes = $user.Notes;
$Office = $user.Office;
$Manager = $user.Manager;

#Условия проверки если не пустая строка удаляем
If ($Title -ne $null)  
{($Title.Remove(50))
Else {If ($Department -ne $null)
{($Department.Remove(50))}
}}

#Собираю обратно таблицу в изначальный вид но с изменеными данными
$a=$ExternalEmailAddress,$FirstName,$LastName,$DisplayName,$StreetAddress,$City,$StateorProvince,$PostalCode,$Phone,$MobilePhone,$Pager,$HomePhone,$Company,$Title,$OtherTelephone,$Department,$CountryOrRegion,$Fax,$Initials,$Notes,$Office,$Manager -join ','

#Для вывода результата перед записью в файл
Write-Output $a

})| Out-File -FilePath 'C:\Laba\knigatest777.csv' -Append -Width 300;


but the result is that the characters are not deleted in the term part and game is written to the file

. I will be glad for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2021-09-28
@myxz

This sounds very wild and incomprehensible

If there, for example, $Title is empty and $Department is not, then write an empty Title and check if $Departme does not exceed 50 characters; if not, also write it in its place; if it exceeds, truncate to 50 characters and write to a file

Your work scheme is overcomplicated.
It must be something like that.
Import-csv ...... |
  Foreach-Object {
    # Тут обработки, которых я не очень понял
    #   Я просто обрезаю title до 50
    if ($_.Title.Length -gt 50) {
       # Вам явно не хватает присвоения результата remove(),
       #   я сделал по-другому, но суть та же
       $_.Title = $_.Title.Substring(0, 50)
    }
    # вывод объекта дальше по конвейеру
    $_
  } |
  # Тут специально предназначенная для вывода csv команда, а не out-file
  Export-csv .....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question