-Split Help

Viewing 1 reply thread
  • Author
    Posts
    • #1572437
      Salvador Diaz
      Participant
      Member Points: 67
      Rank: 1

      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

    • #1572501
      David Figueroa
      Participant
      Member Points: 5,585
      Rank: 3

      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.

      avatar
      • #1572502
        Michael Pietroforte
        Keymaster
        Member Points: 42,263
        Author of the year 2018
        Rank: 4

        Spacing works in text mode if you use pre-HTML tags.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.
© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account