0

It seems so simple. I need a cmdlet to take a two word string, and truncate the first word to just the first character and truncate the second word to 11 characters, and eliminate the space between them. So "Arnold Schwarzenegger" would output to a variable as "ASchwarzeneg"

I literally have no code. My thinking was to

$vars=$var1.split(" ")
$var1=""
foreach $var in $vars{

????

}

I'm totally at a loss as to how to do this, and it seems so simple too. Any help would be appreciated.

1 Answer 1

1

Here is one way to do it using the index operator [ ] in combination with the range operator ..:

$vars = 'Arnold Schwarzenegger', 'Short Name'
$names = foreach($var in $vars) {
    $i = $var.IndexOf(' ') + 1 # index after the space
    $z = $i + 10 # to slice from `$i` until `$i + 10` (11 chars)
    $var[0] + [string]::new($var[$i..$z])
}
$names
Sign up to request clarification or add additional context in comments.

2 Comments

Absolutely perfect, not a solution I'd ever think of. Thank you so much.
@JonathanLudwig my pleasure :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.