我的起始字符串是:
$grp = DL-Test1-Test2-RW"
我的目标是
$grp = "Test1\Test2"
因此,我需要在第一个字符和最后一个“-”字符之间保持字符串。并替换为
更新
我尝试了这个:
$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
最佳答案
假设字符串始终具有这种形式,并且您对第二部分和第三部分感兴趣:
# $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 "\"
编辑-元素的通用数量
$($grp.Split("-") | Select-Object -SkipLast 1 | Select-Object -Last ($grp.Split("-").count - 2)) -join "\"
多行:
$Descritpion = $grp.Split("-")
$Descritpion = $Descritpion | Select-Object -SkipLast 1
$Descritpion = $Descritpion | Select-Object -Last ($grp.Split("-").count - 2)
$Descritpion = $Descritpion-join "\"