1

My start string is:

$grp = DL-Test1-Test2-RW"

My goal is to have

$grp = "Test1\Test2"

So i need to keep string between first and last "-" character. And replace - by \

UPDATED I tried this:

$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion
1

3 Answers 3

2

Assuming string always has this form and you are interested in the 2nd and 3rd parts:

# $grp.Split("x") - split string on character x, creating an array
# $grp.Split("x")[n] - get the nth element of the array
# x,y -join "\" join the array elements x and y into a string, with "\" inbetween
($grp.Split("-")[1],$grp.Split("-")[2]) -join "\"

Edit - For generic number of elements

$($grp.Split("-") | Select-Object -SkipLast 1 | Select-Object -Last ($grp.Split("-").count - 2)) -join "\"

Multiline:

$Descritpion = $grp.Split("-")
$Descritpion = $Descritpion | Select-Object -SkipLast 1
$Descritpion = $Descritpion | Select-Object -Last ($grp.Split("-").count - 2) 
$Descritpion = $Descritpion-join "\"
Sign up to request clarification or add additional context in comments.

4 Comments

Thx but my string is not always this form. So i adapted your code but i need your help to replace function. See my post updated
@Ferfa See update that deals with generic number of elements.
I using PowerShell 2.0 :( :( :( so SkipLast doesn't exist
Replace it with -First ($grp.Split("-").count - 1)
1

just do it:

$grp = "DL-test1-test2-RW"
$arraygrp=$grp.Split("-")
$arraygrp[1..($arraygrp.Count -2)] -join "\"

or this

$grp.Substring($grp.IndexOf('-') +1, $grp.LastIndexOf('-')-$grp.IndexOf('-')-1 ).Replace('-', '\')

Comments

0

You can also do it with regex

$grp = "DL-Test1-Test2-RW"
$regex = "-(.*)-(.*)-"
if ($grp -match $regex){ 
    $Matches[1] + "\" + $Matches[2]
}

If your string can have more groups between start and end, try this

$grp = "DL-Test1-Test2-Test3-Test4-RW"
$regex = "-(.*-){1,999}(.*)-"
if ($grp -match $regex){ 
    $Matches[1].replace('-','\') + $matches[2]  
}

Comments

Your Answer

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.