So what I am trying to achieve is selecting all words from a given string, except the last one. So I have a few strings;
On The Rocks
The Rocks
Major Bananas
I want to select all words, except the last one from every string. I figured out I could use split() to take every word as separate. Though I can't figure it out any further.
Thanks in advance.
In PowerShell string split, to get the last element from the string array, you can use the split operator. Use the -1 index to get the last element from substrings.
PowerShell uses the Split () function to split a string into multiple substrings. The function uses the specified delimiters to split the string into sub strings. The default character used to split the string is the whitespace.
In PowerShell, we can use the split operator (-Split) to split a string text into array of strings or substrings. The split operator uses whitespace as the default delimiter, but you can specify other characters, strings, patterns as the delimiter. We can also use a regular expression (regex) in the delimiter.
Removing objects from arrays should be simple, but the default collection type in Windows PowerShell, an object array (System. Object[]), has a fixed size. You can change objects in the array, but you can't add or delete them, because that would change the size of the array.
$string.SubString(0, $string.LastIndexOf(' '))
Here's how I might do something like this.
$Sample = "String sample we can use"
$Split = $Sample.Split(" ")
[string]$split[0..($Split.count-2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With