Home ยป PowerShell ยป PowerShell Split to Get Last Element

PowerShell Split to Get Last Element

Using the PowerShell string built-in Split() method or split operator, you can easily split string to get the last element. In PowerShell, you can use the -1 to get the last element or index from the array.

In this example, we will discuss how to use the PowerShell string Split() method or split operator to split the string into a string array and get the last element.

Using PowerShell Split() to Get Last Element

Use the PowerShell string Split() method to split the string into multiple substrings.

It returns the string array after splitting based on the delimiter. Use -1 to get the last index from the array.

$sysdate = "01-08-2022" 

# Split the string and use -1 to get last element
$sysdate.Split("-")[-1] 

In the above PowerShell script, the $sysdate variable stores the date in the string format.

To get the year from the string, we have used the PowerShell string Split() method with the Hyphen (โ€“) delimiter.

It splits the strings into string arrays and using the -1 index, it returns the last element from the array.

The output of the above PowerShell string split to get the last element is:

PS C:\> $sysdate = "01-08-2022" 

PS C:\> $sysdate.Split("-")[-1]                                                                                         
2022

PS C:\>                                                                                                                          

Cool Tip: How to use string split regex pattern in PowerShell!

Using the split operator to Get the Last Element

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.

 $sysdate = "01-08-2022"  

# use the split operator to get last element
($sysdate -split '-')[-1]

In the above PowerShell script, the $sysdate variable stores the date in string format. To get the last year, we used the split operator to split the string by the Hyphen (-) delimiter.

It splits the string into multiple substrings based on the Hyphen and using the -1 index, it returns the last element.

The output of the above PowerShell split to get the last element using the split operator is:

PS C:\> $sysdate = "01-08-2022"                                                                                         

PS C:\> ($sysdate -split '-')[-1]                                                                                       
2022

PS C:\> 

Cool Tip: How to split a string on the first occurrence of a substring in PowerShell!

Conclusion

I hope the above article on how to use PowerShell split to get the last element is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.

Leave a Comment