I have a string that has a value for example 22_ABCD Now I only need the ABCD in my parameter. What is the best method to do this in powershell ?
Do I need to use a Split() and then take $stringvalue = Split[1] ? Or is there a function in powershell that does this?
-
Will all strings have the same format (##_aaaa)? Please provide a little more detail.Wonko the Sane– Wonko the Sane2017年02月22日 14:43:40 +00:00Commented Feb 22, 2017 at 14:43
3 Answers 3
Split
is one way to do what you want and can be used like this... where the value between the brackets is the character that you want to use for the split.
$string = "22_ABCD"
$string.Split("_")
Running the above code outputs an array containing two items:
22
ABCD
You can then reference the second item in the array with [1]
([0]
being the first item) like this:
$string.Split("_")[1]
Which outputs just the second item:
ABCD
1 Comment
Regex is a possibility if you are looking for alphanumeric characters rather than just the next set of characters after an underscore.
$x = '22_ABCD_FTG_3'
[regex]::match($x,'([A-Z)]+)').Groups[1].Value
Comments
#method 0, with split operator
$Elements="22_ABCD" -split "_"
$Elements[0]
$Elements[1]
#method 1, with split member
$Elements="22_ABCD".Split('_')
$Elements[0]
$Elements[1]
#method 2, with split member and direct affectation
$Element1, $Element2="22_ABCD".Split('_')
$Element1
$Element2
#method 3, with ConvertFrom-String
$Elements="22_ABCD" | ConvertFrom-String -Delimiter "_" -PropertyNames "Element1", "Element2"
$Elements.Element1
$Elements.Element2
#method 4, with ConvertFrom-Csv
$Elements="22_ABCD" | ConvertFrom-Csv -Delimiter "_" -Header "Element1", "Element2"
$Elements.Element1
$Elements.Element2
#method 5, with regex
$Elements=[regex]::split("22_ABCD", '_')
$Elements[0]
$Elements[1]