You can use PowerShell's Built in -split
operator like:
($String -split " \(")[0]
Above is preferred considering it will work around differences in .Net functionality .Net Framwork versus .Net Core, where the overloads are ordered differently.
Also, and less well known, you can use the other overloads to get .Split()
to split on multiple characters instead of each character:
$string.split([string[]]' (', [StringSplitOptions]::None)[0]
Above the inclusion of [StringSplitOptions]
appears to be required so the overloads will resolve properly. Attempting to cast the delimitator only will result in an error.
Note: the available overloads in Windows PowerShell:
OverloadDefinitions
-------------------
string[] Split(Params char[] separator)
string[] Split(char[] separator, int count)
string[] Split(char[] separator, System.StringSplitOptions options)
string[] Split(char[] separator, int count, System.StringSplitOptions options)
string[] Split(string[] separator, System.StringSplitOptions options)
string[] Split(string[] separator, int count, System.StringSplitOptions options)
And in PowerShell Core:
OverloadDefinitions
-------------------
string[] Split(char separator, System.StringSplitOptions options)
string[] Split(char separator, int count, System.StringSplitOptions options)
string[] Split(Params char[] separator)
string[] Split(char[] separator, int count)
string[] Split(char[] separator, System.StringSplitOptions options)
string[] Split(char[] separator, int count, System.StringSplitOptions options)
string[] Split(string separator, System.StringSplitOptions options)
string[] Split(string separator, int count, System.StringSplitOptions options)
string[] Split(string[] separator, System.StringSplitOptions options)
string[] Split(string[] separator, int count, System.StringSplitOptions options)
You can check this answer and the surrounding discussion for more information. You can also find a very robust explanation of the pitfalls of using .Split()
in this answer.
Note: You shouldn't have to run the .ToString()
method on something that's already a string. So I removed that from the above examples.