James Larson
James Larson

Reputation: 3

How to extract substring in Powershell

I have multiple strings. They will be similar to

DEVSRC\2019\REL\19-REL-07\Sales\CustomerFlow\company.Presales.CustomerFlow.Web.UI.CustomerMobile\App_Themes\Bundles

and

DEVSRC\2019\REL\19-REL-07\Policy\XPM\Insured\company.PolicyManagement.WebSite.Customer.Components\content

In powershell I need to remove the "DEVSRC\2019\REL\19-REL-07\" from beginning And Everything after the "company.?.?.?"

I'm new to power shell and have been trying for a couple days

I have tried trim, substring, etc, but noting seems to work.

output should be

$mystring = "Sales\CustomerFlow\company.Presales.CustomerFlow.Web.UI.CustomerMobile"

or

mystring = "Policy\XPM\Insured\company.PolicyManagement.WebSite.Customer.Components"

Upvotes: 0

Views: 84

Answers (2)

Lee_Dailey
Lee_Dailey

Reputation: 7489

this uses a named capture group and a lazy capture that stops before the 1st \ after \companies. in order to get the wanted part of the text. it is fragile in that it depends on a very specific pattern, but your two samples fit that pattern. [grin]

$InStuff = @'
DEVSRC\2019\REL\19-REL-07\Sales\CustomerFlow\company.Presales.CustomerFlow.Web.UI.CustomerMobile\App_Themes\Bundles
DEVSRC\2019\REL\19-REL-07\Policy\XPM\Insured\company.PolicyManagement.WebSite.Customer.Components\content
'@ -split [System.Environment]::NewLine

foreach ($IS_Item in $InStuff)
    {
    $Null = $IS_Item.Replace('DEVSRC\2019\REL\19-REL-07\', '') -match '(?<Wanted>.+\\company.+?)\\.+'

    $Matches.Wanted
    }

output ...

Sales\CustomerFlow\company.Presales.CustomerFlow.Web.UI.CustomerMobile
Policy\XPM\Insured\company.PolicyManagement.WebSite.Customer.Components

Upvotes: 1

AdminOfThings
AdminOfThings

Reputation: 25031

If the number of \ characters is predictable, you can use -Split and -Join to make this a lot cleaner.

$s = "DEVSRC\2019\REL\19-REL07\Sales\CustomerFlow\company.Presales.CustomerFlow.Web.UI.CustomerMobile\App_Themes\Bundles"
($s -split "\\")[4..6] -join '\'

Upvotes: 1

Related Questions