Split

The Split method has a relative in PowerShell: the -split operator. The -split operator expects a regular expression, whereas the split method for a string expects an array of characters by default:

$myString = 'Surname,GivenName' 
$myString.Split(',') 

When splitting the following string based on a comma, the resulting array will have three elements. The first element is Surname, the last is GivenName. The second element in the array (index 1) is blank:

$string = 'Surname,,GivenName' 
$array = $string.Split(',') 
$array.Count    # This is 3 
$array[1]       # This is empty 

This blank value may be discarded by setting the StringSplitOptions argument of the Split method:

$string = 'Surname,,GivenName' 
$array = $string.Split(',', [StringSplitOptions]::RemoveEmptyEntries) 
$array.Count    # This is 2 

When using the Split method in this manner, individual variables may be filled from each value as follows:

$surname, $givenName = $string.Split(',', [StringSplitOptions]::RemoveEmptyEntries) 

The Split method is powerful, but care is required when using its different arguments. Each of the different sets of arguments works as follows:

PS> 'string'.Split

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)

PowerShell can create a character array from a string, or an array of strings, provided that each string is no more than one character long. Both of the following statements will result in an array of characters (char[]):

[char[]]$characters = [string[]]('a', 'b', 'c') [char[]]$characters = 'abc' 

When the Split method is used as follows, the separator is any (and all) of the characters in the string. The result of the following expression is an array of five elements (one, <empty>, two, <empty>, and three):

$string = 'one||two||three' 
$string.Split('||') 

To split using a string, instead of an array of characters, PowerShell must be forced to use this overload definition:

string[] Split(string[] separator, System.StringSplitOptions options)

This can be achieved with the following cumbersome syntax:

$string = 'one||two||three' 
$string.Split([String[]]'||', [StringSplitOptions]::None) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.217