-Split Help
- This topic has 2 replies, 3 voices, and was last updated 2 months, 2 weeks ago by
Michael Pietroforte.
- AuthorPosts
- Mon, Jul 10 2023 at 3:27 pm #1572437
Looking for some help. I have a small script to create user accounts on a closed network. I prompt for Full Name and use split to grab first and last name and just the middle initial. However if there is no middle initial my script doesn’t account for that and throws errors. Below is a snippet of the code.
$Name = Read-Host “enter users full name”
$Name -split “s”,3
$First = ($Name -split “s”,0)[0]
$Initial = ($Name -split “s”,0)[1]
$Last = ($Name -split “s”,0)[2]So if the user has no middle initial the $Initial variable returns the last name, which is what is supposed to happen according to the code, but what I need for it to do is ignore the $initial if it is null and grab the last name for the $last variable. Hopefully that makes sense. Thanks
- Tue, Jul 11 2023 at 6:28 pm #1572501
Shouldn’t be too hard..
$Name = Read-Host -Prompt "Enter the user's full name" $Names = $Name -split ' ' switch ($names.Count) { 3 { $UserParams = @{ givenName = $Names[0] Initials = $Names[1] sn = $Names[2] DisplayName = $Names -join ' ' } break } 2 { $UserParams = @{ givenName = $Names[0] Initials = '' sn = $Names[2] DisplayName = $Names -join ' ' } break } 1 { throw 'Not enough names supplied; try again } default { throw 'Either 0 names or too many names supplied; try again' } }
My apologies, it won’t keep the spacing for some reason
David F.
- Wed, Jul 12 2023 at 9:41 am #1572502
Spacing works in text mode if you use pre-HTML tags.
- AuthorPosts
- You must be logged in to reply to this topic.