0

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?

Cœur
39k25 gold badges206 silver badges281 bronze badges
asked Feb 22, 2017 at 14:42
1
  • Will all strings have the same format (##_aaaa)? Please provide a little more detail. Commented Feb 22, 2017 at 14:43

3 Answers 3

2

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
answered Feb 22, 2017 at 14:48

1 Comment

Great, didn't know you could split the string directly. Thats great :)
0

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
answered Feb 22, 2017 at 15:51

Comments

0
#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]
answered Feb 22, 2017 at 17:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.