-1

I have a CSV that is manually updated occasionally with ID's of users here at work. I have code that does a compare on the list but some of the ID's have spaces after them so they aren't matching.

How do I do a data integrity check on this CSV to make sure only the ID names are listed? In other words remove all the spaces.

2 Answers2

1

The .trim() string method will remove starting or trailing spaces. There is also a .trimend() method for only trailing.

$TrimmedCSV = Import-CSV C:\example.csv | ForEach-Object {$_.ID = $_.ID.Trim(); $_} 
$TrimmedCSV | Export-CSV C:\example.csv -NoTypeInformation

Likewise as Matt mentions, there is also .trimstart(). You can also trim characters besides space. For example, .trim('a').

BenH
  • 9,766
  • 1
  • 22
  • 35
  • This doesn't work for me. In my csv the header is $ids and I tried trim and trimend () neither works when I run and then pull up the value I still see characters after. – socavalier Aug 11 '17 at 19:32
  • @socavalier Please post your code, as my code tests working: `$TrimmedCSV[1].id.length` 1 `$unTrimmedCSV[1].id.length` 2 – BenH Aug 11 '17 at 19:43
0

You can compare after stripping the spaces very easily:

(" SAM 500 " -replace ' ', '') -eq "SAM500"

Or, without seeing your code probably closer to:

($User -replace ' ','') -eq $oldId

Alternatively, (as mentioned) if you need to preserve some spaces, but ensure leading and trailing spaces are removed, use .Trim()

$NewName.Trim() -eq $prviousName

Or if you want to get a little creative, you could also use -Match and regex:

$newName -match "\s+(\b$oldName\b)+\s+"
Austin T French
  • 5,022
  • 1
  • 22
  • 40
  • 2
    _spaces after them_. Pretty sure you don't want to be messing with spaces on the inside as well. – Matt Aug 10 '17 at 21:17
  • @Matt I thought the same but being a username... I'll add trim as well though ad it would be a clearer answet – Austin T French Aug 10 '17 at 22:13
  • 2
    Depending on the system username can have spaces. I have an AD account that makes my OCD go crazy since it has _two_ spaces in it. Who does that. – Matt Aug 10 '17 at 22:15
  • @Matt I seem to remember an old best practices to NOT do that, specifically a MS approach. – Austin T French Aug 11 '17 at 02:30