I have a powershell script to “convert” txt file into xlsx. The text in the txt file has a very specific structure so it can be worked with. It looks like this:
Student:: Doe John
Username:: doejohn24
Password:: password
The fact that passwords are stored in an uprotected txt file in plain text is the reason why I want to convert it to excel, which can be at least protected by a password and is also more easily managable. The whole system of storing passwords for users instead of them being able to change it seems ridiculous to me but that’s how the system is set in the school. But at least I want to protect them a little.
The script extracts surname, name, username and password from each block and writes the values to cells in excel file after it creates a new sheet and prefills header row.
So, the script works exactly as intended, but I encountered an issue. I extract the name, surname, username and password by a split method (for example $name = $fileContent[$i].Split(" ")[2]
) But occasionally there are two spaces between words and then the split method obviously points to an incorrect item. Is there a way around it or do I have to check the results each time to make sure it’s correct and possibly correct manually?
1
There is a big difference between .split() method and -Split function.
.split process input as a simple text:
("One two three Four").split(" ")
One
two
three
four
-split operator process input as a regular expression, you can use it to treat double space:
"One two three Four" -split " +"
One
two
three
Four
Alain
Replace all multiple spaces with single spaces and then split:
$ExampleOne = "Student:: Doe John"
$ExampleTwo = "Student:: Doe Jane"
($ExampleOne -replace ' {2,}', ' ' -split ' ')[2] # John
($ExampleTwo -replace ' {2,}', ' ' -split ' ')[2] # Jane