Jonathan Ludwig
Jonathan Ludwig

Reputation: 17

Truncate, Convert String and set output as variable

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.

Upvotes: 0

Views: 92

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60110

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

Upvotes: 1

Related Questions