I'm very new to Powershell ISE and I'm not sure how to go about doing this.
I want to take strings (uxxxx axxxx name email) and have it return as a table with username, admin, and name (want to eventually automate emails). My code is currently like this:
$users = Get-Content ".\FileName.txt"
$line = "Username, Admin, Name, Email"
$parts = $line.Split(" ")
$Test = Foreach ($user in $users) {
Select-Object Username, Admin, Name
}
$Test | Sort-Object -Property Name | Out-GridView
This is just a watered down version of the code since it will be going through domains and authentication processes, but I was hoping someone could just help me get the table to work for now.
CodePudding user response:
With what you've shown, the John Doe
part means you can't use Import-Csv
or easily split on spaces without having to reassemble that column after.
I am thinking: split on spaces twice from the left, and then with the rest of the string find the last space from the right and pick out around that. Leaving the John Doe column with as many spaces as it has. (This will only work if you can guarantee the username, admin name and email never have spaces in them. If more than one column could have a space in it, you have no obvious way to tell spaces as column separators from spaces as data).
$rows = Get-Content -Path '.\FileName.txt'
$users = foreach ($r in $rows) {
# Take 2 columns from the left, and store the rest
$user, $admin, $rest = $r.Split(' ', 3)
# Walk back from the right to the first space
# and pick either side of it
$i = $rest.LastIndexOf(' ')
$name = $rest.Substring(0, $i)
$email = $rest.Substring($i 1)
# Build an output that can work with Out-GridView
[PSCustomObject]@{
Username = $user
Admin = $admin
Name = $name
Email = $email
}
}
$users | Out-GridView