Eric Eric - 3 months ago 18
PowerShell Question

PowerShell extract characters from string

I have a list of user names in a .csv file. Looks like this

PC,User
comp-1,john.doe
PC-2,steven.smith
MAC-1,betty.crocker


and I would like to extract the first letter of the first and last name to put into another variable. Not sure how to accomplish this. Here is my code that will get me the first letter.

$PepCSV = import-csv C:\pep.csv
foreach($X in $PepCSV)
{
$UserName = $X.User
$UserInt = $UserName.Substring(0,1)
Write-Output "UserName = $UserName `n UserInt = $UserInt"
}


The output is this

UserName = john.doe
UserInt = j
UserName = steven.smith
UserInt = s
UserName = betty.crocker
UserInt = b


How can I get the second letter for UserInt?

Answer

You can get the first letter of the lastname by this codelet:

 $PepCSV = import-csv C:\pep.csv 
 foreach($X in $PepCSV)
 {
 $UserName = $X.User
 $UserInt = $UserName.Substring(0,1) + ($Username -split '\.')[1].substring(0,1)
 Write-Output "UserName = $UserName `n UserInt = $UserInt"
 } 
Comments